-
Notifications
You must be signed in to change notification settings - Fork 509
Create New Map Tool
fuzhenn edited this page Oct 12, 2017
·
1 revision
A map tool takes over interactions of a map to enable the map with more functions besides panning and zooming. For exmaple:
- A DrawTool to draw circles/rectangles/linestrings/polygons on the map with mouse.
- A DistanceTool to do measurements on the map with mouse.
Same with controls, to create a map tool, the only thing you need to do is to extend maptalks.MapTool and add some interface methods:
- onAdd: optional, a callback method to do some prepares before enabled when the map tool is added to a map
- onEnable: optional, called when the map tool is enabled, used to setup the context such as adding more event listeners other than the map, disabling map's default handlers (draggable, scrollWheelZoom, etc) and creating temporary layers.
- getEvents: required, provide a key-value event map to add event listeners on the map. The key is the event types and value is the listener function. The listeners will be removed when the map tool is disabled.
- onDisable: optional, called when the map tool is disabled, used to cleanup such as removing event listeners, enable map's original handlers and remove temporary layers.
A map tool occupies a map which means when a map tool is added to a map, the previous one (if there is) will be disabled immediately.
Here is an example map tool to add markers by left clicking and clear the map by right clicking:
var CustomTool = maptalks.MapTool.extend({
initialize: function () {
},
//add an temporary VectorLayer to draw markers.
onEnable: function () {
var layerId = maptalks.internalLayerPrefix + '_marker_map_tool';
this._markerLayer = new maptalks.VectorLayer(layerId)
.addTo(this.getMap());
},
//the event listeners to add to the map
getEvents: function () {
return {
'click': this._onClick,
'contextmenu': this._onRighClick
};
},
// remove the temporary VectorLayer when disabled
onDisable: function () {
if (this._markerLayer) {
this.getMap().removeLayer(this._markerLayer);
}
},
//click to add markers
_onClick: function (param) {
this._markerLayer.addGeometry(new maptalks.Marker(param.coordinate));
},
//right click to clear the layer
_onRighClick: function (param) {
this._markerLayer.clear();
}
});
var customTool = new CustomTool().addTo(map);
Check out the live demo here.