Adding multiple Leaflet layers resulted in inaccurately positioned containers

Viewed 157

I have the following code to extend Leaflet layer for adding custom layers.

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);
};

However, when I tried to add two markers and two custom layers at the same coordinates respectively, the second layer seems to be positioned wrongly.

The layers are added with the following code:

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

Any advice on this? CodePen is here. Thanks for your help!

1 Answers

For those who might need this piece of information, I have found out the problem. You need to set the position of the container to absolute by doing:

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);
},

See the link to the leaflet.css for the necessary styles. :D

Related