Search code examples
javascriptleaflet

Is there a way to set position for specific layer instead of all layers on the map?


One specific layer requires the following block to be positioned properly in relation to map.

const mapSize = map.getSize();
const globalPos = L.DomUtil.getPosition(map.getPane("mapPane"));
const topLeft = globalPos.multiplyBy(-1);
const bottomRight = topLeft.add(mapSize);
L.DomUtil.setPosition(map.getPane(this.options.pane), topLeft);

This block is getting called on every map view update.

The problem is: when I try to add another layer (GeoJSON/JSON), which doesn't require such adjustment, it's also being affected by DomUtil position and is placed improperly on the map. Is there a way to set position for specific layer only, or perhaps to offset the position of GeoJSON layer somehow to compensate for the changes to position set through DomUtil?


Solution

  • Instead of directly setting the position of the entire pane, set the position of individual layers by adjusting their container points allowing you to control the position of specific layers independently.

    const customLayer = L.geoJSON(yourGeoJSONData, {
      onAdd: function (map) {
        const mapSize = map.getSize();
        const globalPos = L.DomUtil.getPosition(map.getPane("mapPane"));
        const topLeft = globalPos.multiplyBy(-1);
        const bottomRight = topLeft.add(mapSize);
        const containerPoint = map.latLngToLayerPoint(this.getLatLng());
        const adjustedContainerPoint = containerPoint.add(topLeft);
        L.DomUtil.setPosition(this.getElement(), adjustedContainerPoint);
      }
    }).addTo(map);