Skip to content

Create New UI Component

fuzhenn edited this page Oct 12, 2017 · 1 revision

Differenece between maptalks.Control and maptalks.UIComponent:

  • Control is placed by pixel position, but an UI Component is placed by geographic coordinate
  • UI Component can be set to be singleton globally if its options.single is true

Same with controls, to create an UI Component, what you need to do is to extend maptalks.ui.UIComponent and add necessary methods:

  • buildOn: required, to create UI Component's HTML DOM Element.
  • getOffset: optional, returns the dom element's position offset, can be useful when offset is dynamic.
  • getEvents: optional, provide an event map to register event listeners .
  • onDomRemove: optional, a callback when UI's dom is removed.
  • onAdd: optional, a callback when UI Component is added to map.
  • onRemove: optional, a callback when UI Component is removed from map.

An example:

const options = {
  'content'  : '',
  //override parent's animationOnHide option
  'animationOnHide' : false
};

class MyUI extends maptalks.ui.UIComponent {

  constructor(coordinate, options) {
    super(options);
    this._coordinate = coordinate;
  }

  buildOn(map) {
    var dom = document.createElement('div');
    dom.className = 'my-ui';
    dom.innerText = this.options['content'];
    return dom;
  }

  getOffset() {
    var size = this.getSize();
    //move anchor to center of UI
    return new maptalks.Point(-size.width / 2, -size.height / 2);
  }

  getEvents() {
    return {
      'zoomend' : this._flash
    };
  }

  onAdd() {
    console.log('MyUI is added');
  }

  onRemove() {
    if (this._flashTimeout) {
      clearTimeout(this._flashTimeout);
    }
  }

  _flash() {
    //flash after zooming.
    this.hide();
    this._flashTimeout = setTimeout(() => {
      this.show(this._coordinate);
    }, 200);
  }
}

MyUI.mergeOptions(options);

Check out the live demo here.

The abstract UIComponent class has some useful methods, please refer to UIComponent's API for more details.