Search code examples
javascriptdictionaryleaflet

Leaflet center popup AND marker to the map


I want center my marker on popup open.. and centering map not in marker latlng, but on center of marker and popup! The problem is that popup has dinamic content(loaded on click).

The map size is full display size in a mobile device! I'm just used autoPanPadding option in popup but not sufficient

Refer to follow picture:

popup centered in leaflet map


Solution

  • Using fitzpaddy's answer I was able to make this code which works and is much more flexible.

    map.on('popupopen', function(e) {
        var px = map.project(e.target._popup._latlng); // find the pixel location on the map where the popup anchor is
        px.y -= e.target._popup._container.clientHeight/2; // find the height of the popup container, divide by 2, subtract from the Y axis of marker location
        map.panTo(map.unproject(px),{animate: true}); // pan to new center
    });