Map.options
介绍一下Map.options的使用方法,以map.options.worldCopyJump为例
可看出如果这个使能worldCopyJump,在pan到另外一个world时候将所有overlay复制一次。
var Drag = Handler.extend({
addHooks: function () {
if (!this._draggable) {
var map = this._map;
this._draggable = new Draggable(map._mapPane, map._container);
this._draggable.on({
dragstart: this._onDragStart,
drag: this._onDrag,
dragend: this._onDragEnd
}, this);
this._draggable.on('predrag', this._onPreDragLimit, this);
if (map.options.worldCopyJump) {
this._draggable.on('predrag', this._onPreDragWrap, this);
map.on('zoomend', this._onZoomEnd, this);
//将mapPane上的所有overlayer重绘一遍
map.whenReady(this._onZoomEnd, this);
}
}
addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
this._draggable.enable();
this._positions = [];
this._times = [];
},
_onZoomEnd: function () {
var pxCenter = this._map.getSize().divideBy(2),
pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
},
});
从代码中看实在drag事件中,如果worldCopyJump使能,在drag动作之后,map地图重新定位0,0原点,可以导致像素原点与地图原点重新对应。
whenReady就是当地图上至少有一层图层初始化结束,那就触发this._onZoomEnd。
Methods
Map这个类提供了挺多Method,在官方API中可以看到,Method分为:
- Methods for Layers and Controls;
- Methods for modifying map state;
- Geolocation methods;
- Other Methods;
- Methods for Getting Map State;
- Conversion Methods;
在map里面定义的API基本上涵盖一下几部分
- setView、setZoom更新map状态的方法
- getCenter、getZoom、getPixelOrigin获得map状态的方法
- getContainer、getPanes获得map中元素的方法
- project、unproject、layerPointToLatLng、latLngToLayerPoint坐标转换方法(与crs有关)
- addHandler、addControl此类扩展接口方法
也就是说我们做的marker、layer、control全部都要addToMap。我们看一下control是如何add到map上的。
var Control = Class.extend({
// @section
// @aka Control options
options: {
// @option position: String = 'topright'
// The position of the control (one of the map corners). Possible values are `'topleft'`,
// `'topright'`, `'bottomleft'` or `'bottomright'`
position: 'topright'
},
// @method setPosition(position: string): this
// Sets the position of the control.
setPosition: function (position) {
var map = this._map;
if (map) {
map.removeControl(this);
}
this.options.position = position;
if (map) {
map.addControl(this);
}
return this;
},
// @method addTo(map: Map): this
// Adds the control to the given map.
addTo: function (map) {
this.remove();
this._map = map;
var container = this._container = this.onAdd(map),
pos = this.getPosition(),
corner = map._controlCorners[pos];
addClass(container, 'leaflet-control');
if (pos.indexOf('bottom') !== -1) {
corner.insertBefore(container, corner.firstChild);
} else {
corner.appendChild(container);
}
return this;
},
});
/* Every control should extend from `L.Control` and (re-)implement the following methods.
*
* @method onAdd(map: Map): HTMLElement
* Should return the container DOM element for the control and add listeners on relevant map events.
* Called on [`control.addTo(map)`](#control-addTo).
*/
调用addTo()这个函数可以看到,我们经常在control里面去重定义onAdd()的函数,在onAdd()函数中定义leaflet control控件在加载时的动作,可以在其中增加leaflet control的DOM元素,也可以增加map的动作相应事件。以MousePosition这个plugin为例子,在onAdd中定义了dom与event。当然还有很多control在initialize函数中定义元素初始化,这是依赖于class中的方法,可以是可以就是太过底层方法,使用起来较为复杂。
L.Control.MousePosition = L.Control.extend({
onAdd: function (map) {
this._container = L.DomUtil.create('div', 'leaflet-control-mouseposition');
L.DomEvent.disableClickPropagation(this._container);
map.on('mousemove', this._onMouseMove, this);
this._container.innerHTML=this.options.emptyString;
return this._container;
},
});
Methods for modifying map state
// @section Methods for modifying map state
// @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
// Sets the view of the map (geographical center and zoom) with the given
// animation options.
setView: function (center, zoom, options) {
zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
options = options || {};
this._stop();
if (this._loaded && !options.reset && options !== true) {
if (options.animate !== undefined) {
options.zoom = extend({animate: options.animate}, options.zoom);
options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
}
// try animating pan or zoom
var moved = (this._zoom !== zoom) ?
this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
this._tryAnimatedPan(center, options.pan);
if (moved) {
// prevent resize handler call, the view will refresh after animation anyway
clearTimeout(this._sizeTimer);
return this;
}
}
// animation didn't start, just reset the map view
//map setview就是重置一次中心位置
this._resetView(center, zoom);
return this;
},
// @section Map state change events
_resetView: function (center, zoom) {
//将_mapPane重置到屏幕左上角
//对应的element元素 leaflet-pane leaflet-map-pane
setPosition(this._mapPane, new Point(0, 0));
var loading = !this._loaded;
this._loaded = true;
zoom = this._limitZoom(zoom);
this.fire('viewprereset');
var zoomChanged = this._zoom !== zoom;
this
._moveStart(zoomChanged)
._move(center, zoom)
._moveEnd(zoomChanged);
// @event viewreset: Event
// Fired when the map needs to redraw its content (this usually happens
// on map zoom or load). Very useful for creating custom overlays.
this.fire('viewreset');
// @event load: Event
// Fired when the map is initialized (when its center and zoom are set
// for the first time).
if (loading) {
this.fire('load');
}
},
_getNewPixelOrigin: function (center, zoom) {
//屏幕视图中中间位置像素
var viewHalf = this.getSize()._divideBy(2);
//得到map的中点位置像素,_subtract是像素this.x -= point.x;this.y -= point.y;
//算出屏幕中心与map中心的差值,把这个差值算入到Mappane的偏移量上,就是简单的加减
return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
},
_move: function (center, zoom, data) {
if (zoom === undefined) {
zoom = this._zoom;
}
var zoomChanged = this._zoom !== zoom;
this._zoom = zoom;
this._lastCenter = center;
//重新算中心偏量
this._pixelOrigin = this._getNewPixelOrigin(center);
// @event zoom: Event
// Fired repeatedly during any change in zoom level, including zoom
// and fly animations.
if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
this.fire('zoom', data);
}
// @event move: Event
// Fired repeatedly during any movement of the map, including pan and
// fly animations.
return this.fire('move', data);
},
Conversion Methods
// @method project(latlng: LatLng, zoom: Number): Point
// Projects a geographical coordinate `LatLng` according to the projection
// of the map's CRS, then scales it according to `zoom` and the CRS's
// `Transformation`. The result is pixel coordinate relative to
// the CRS origin.
project: function (latlng, zoom) {
zoom = zoom === undefined ? this._zoom : zoom;
return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
},
// @method unproject(point: Point, zoom: Number): LatLng
// Inverse of [`project`](#map-project).
unproject: function (point, zoom) {
zoom = zoom === undefined ? this._zoom : zoom;
return this.options.crs.pointToLatLng(toPoint(point), zoom);
},
unproject、project有将LatLng的地理坐标转化层Map像素坐标,根据crs的计算进行转化成像素坐标,当我们在zoom=4时,latlng=[0,0] 在Map上的位置是[2048,2048] = 256*2^(zoom-1) - [0,0],crs坐标转换方法看我另一篇博文,不再次赘述了。
像素Point[0,0]作为屏幕的左上角绘制一个小圆点。
L.circle(latlng, {radius: 3, color: 'red', fillColor: '#f03', fillOpacity: 1}).addTo(map);
同样我们可以在mappane上使用元素方法增加一个小直角。
var pane = map.getPane('markerPane');
var paneCorner = document.createElement('div');
paneCorner.style.width = '12px';
paneCorner.style.height = '12px';
paneCorner.style.borderTop = '2px red solid';
paneCorner.style.borderLeft = '2px red solid';
pane.appendChild(paneCorner);
当map出现_move动作时,实际的作用是重置地图的中心,在mapPane上整体产生偏移,说明在markerPane上增加元素的效果是一样的,当出现_zoom动作时,小直角的位置没有发生变化,小圆点位置变化了,也不难理解,因为circle在markerPane中是以Latlng存在的,在map的_zoom动作时,marker上的对象会将Latlng重新计算成Point(实际上也就是pixel coordinate,详见leaflet DOC中对Point的介绍)