添加多个Leaflet层会导致容器放置不正确

时间:2018-11-12 06:15:01

标签: javascript leaflet

我有以下代码来扩展Leaflet层以添加自定义层。

L.CustomLayer = L.Layer.extend({
    initialize: function (latlng, options) {
        this._latlng = L.latLng(latlng);
        L.Util.setOptions(this, options);
    },
    onAdd: function (map) {
        this._div = document.createElement("div");
        this._div.style.padding = "8px";
        this._div.style.border = "2px solid grey";
        this._div.style.borderRadius = "2px";
        this.getPane().appendChild(this._div);
        this._update();
        map.on("zoomend viewreset", this._update, this);
    },
    onRemove: function (map) {
        L.DomUtil.remove(this._div);
        map.off("zoomend viewreset", this._update, this);
    },
    _update: function () {
        var pos = this._map.latLngToLayerPoint(this._latlng);
        L.DomUtil.setPosition(this._div, pos);
    }
});

L.customLayer = function (latlng, options) {
    return new L.CustomLayer(latlng, options);
};

但是,当我尝试分别在同一坐标处添加两个标记和两个自定义层时,第二层似乎放置错误。

使用以下代码添加图层:

var customLayer1 = L.customLayer().setPosition([3.139003, 101.686852]).addTo(map);
var customLayer2 = L.customLayer().setPosition([6.121070, 100.369797]).addTo(map);

对此有何建议? CodePen是here。感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

对于那些可能需要这些信息的人,我已经找到了问题所在。您需要执行以下操作将容器的位置设置为absolute

onAdd: function (map) {
    this._div = document.createElement("div");
    this._div.style.padding = "8px";
    this._div.style.border = "2px solid grey";
    this._div.style.borderRadius = "2px";

    // Set "position" to "absolute" manually for "top" and "left"
    // to work. Alternatively, apply CSS styles for leaflet-layer
    // class by adding class for all the necessary styles
    // this._div.style.position = "absolute";

    // See the link below for all the styles included
    // https://github.com/Leaflet/Leaflet/blob/master/dist/leaflet.css
    L.DomUtil.addClass(this._div, "leaflet-layer");

    this.getPane().appendChild(this._div);
    this._update();
    map.on("zoomend viewreset", this._update, this);
},

有关必要样式,请参见leaflet.css的链接。 :D