Leaflet center popup AND marker to the map

stefcud picture stefcud · Mar 20, 2014 · Viewed 14.2k times · Source

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

Answer

Dan Mandle picture Dan Mandle · May 30, 2014

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