Skip to content

Latest commit

 

History

History
135 lines (88 loc) · 3.65 KB

打开一个popup不关闭另一个(参考源码覆盖方法).md

File metadata and controls

135 lines (88 loc) · 3.65 KB

目的

leaflet打开多个popup时不会自动关闭,即保持多个popup同时打开的状态。

leaflet同时打开多个popup

看到上面这个还要钱,还不如自己写一个开源出来呢。

原理

查看leaflet 源码中的popup打开代码,位置在src/layer/popup.js

Map.include({
	// @method openPopup(popup: Popup): this
	// Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
	// @alternative
	// @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
	// Creates a popup with the specified content and options and opens it in the given point on a map.
	openPopup: function (popup, latlng, options) {
		if (!(popup instanceof Popup)) {
			popup = new Popup(options).setContent(popup);
		}

		if (latlng) {
			popup.setLatLng(latlng);
		}

		if (this.hasLayer(popup)) {
			return this;
		}

		if (this._popup && this._popup.options.autoClose) {
			this.closePopup();
		}

		this._popup = popup;
		return this.addLayer(popup);
	},

发现openPopup是L.map中的一个方法,且在打开本次的popup之前会调用

if (this._popup && this._popup.options.autoClose) {
			this.closePopup();
		}

关闭之前 打开的popup。

因此修改如下

 Map2 = L.Map.extend({
        // 覆盖源码
        openPopup: function (popup, latlng, options) {
            if (!(popup instanceof L.Popup)) {
                popup = new L.Popup(options).setContent(popup);
            }

            if (latlng) {
                popup.setLatLng(latlng);
            }

            if (this.hasLayer(popup)) {
                return this;
            }

            if (this._popup && this._popup.options.autoClose) {
//                this.closePopup(); 修改了这块
            }

            this._popup = popup;
            return this.addLayer(popup);
        }
    });

    map2 = function (id, options) {
        return new Map2(id, options);
    };

     var leafletMap = map2('mapDiv').setView([51.505, -0.09], 13);
    //图层
    L.tileLayer(url, {
        maxZoom: 18,
        attribution: attr,
        id: 'mapbox.streets'
    }).addTo(leafletMap);

    /**
     *
     */

    L.marker([51.5, -0.09]).addTo(leafletMap)
        .bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();
    L.marker([51.5, -0.08]).addTo(leafletMap)
        .bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();

新发现

看源代码

if (this._popup && this._popup.options.autoClose) {
			this.closePopup();
		}

发现指定autoClose=false也可以达到同样的效果。汗。不过能够读一下源码也是不错的。

源代码

取消自动关闭popup 扩展代码版

取消自动关闭popup antoclose版