Leaflet源码解析系列(六-5):Map 对象解读——获取 map state 的方法

185 阅读2分钟

用来获取地图的 zoomcenterboundssize,以及一些内部方法,获取各个坐标系下的坐标。

export const Map = Evented.extend({
  // ......
  // 获取 map state
	/** 返回 map 当前的 zoom 层级 */
	getZoom() {
		return this._zoom;
	},

	/** 返回 map 当前的中心点经纬度 */
	getCenter() {
		this._checkIfLoaded();

		if (this._lastCenter && !this._moved()) {
			return this._lastCenter.clone();
		}
		return this.layerPointToLatLng(this._getCenterLayerPoint());
	},

	/** 返回 map 当前的经纬度视野 */
	getBounds() {
		// 获取像素范围
		const bounds = this.getPixelBounds(),
				// 将像素坐标转换为经纬度
		    sw = this.unproject(bounds.getBottomLeft()),
		    ne = this.unproject(bounds.getTopRight());

		return new LatLngBounds(sw, ne);
	},

	/** 获取最小 zoom,如果 option 里没有设置,就用 layer 的最小 zoom,默认是 0 */
	getMinZoom() {
		return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
	},

	/**  获取最大 zoom,如果 option 里没有设置,就用 layer 的最大 zoom,默认是无限大,一般加了瓦片图层,都会限制图层的最大缩放级别 */
	getMaxZoom() {
		return this.options.maxZoom === undefined ?
			(this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
			this.options.maxZoom;
	},

  /** 获取 map 的 maxZoom 和 minZoom 间隔 */
  _getZoomSpan() {
    return this.getMaxZoom() - this.getMinZoom();
  },
  
	/** 返回 map 容器当前的像素大小 */
	getSize() {
		if (!this._size || this._sizeChanged) {
			// 因为可能监听了 resize,所以要判断下 map 容器的大小是否变了
			this._size = new Point(
				this._container.clientWidth || 0,
				this._container.clientHeight || 0);

			this._sizeChanged = false;
		}
		// clone 了一份,防止误改
		return this._size.clone();
	},

	/** 返回 map 当前的投影 bounds(像素单位),注意:并不是 size (sometimes useful in layer and overlay implementations)*/
	getPixelBounds(center, zoom) {
		const topLeftPoint = this._getTopLeftPoint(center, zoom);
		return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
	},

	/** 获取左上角的投影坐标(像素单位) */
	_getTopLeftPoint(center, zoom) {
		// 如果指定了 center 和 zoom
		const pixelOrigin = center && zoom !== undefined ?
		  // 计算当前 center 和 zoom 的 pixelOrigin
			this._getNewPixelOrigin(center, zoom) :
			// 直接返回 map 的 _pixelOrigin
			this.getPixelOrigin();
		return pixelOrigin.subtract(this._getMapPanePos());
	},

	/** 获取指定 center 和 zoom 的投影坐标(像素单位) */
	_getNewPixelOrigin(center, zoom) {
		const viewHalf = this.getSize()._divideBy(2);
		return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
	},

	// TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to the map pane? 
	// "left point of the map layer" can be confusing, specially since there can be negative offsets.
	// 返回 map 当前左上角的投影坐标(像素单位) (useful in custom layer and overlay implementations).
	getPixelOrigin() {
		this._checkIfLoaded();
		return this._pixelOrigin;
	},

	/** 返回 map 当前bounds 对应的投影坐标范围(像素单位),如果没有传入 zoom,就用当前的 zoom */
	getPixelWorldBounds(zoom) {
		return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
	},
  // ......
})