[GIS] Leaflet center Marker AND Popup on Map viewport

javascriptleafletpopupweb-mapping

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:

enter image description here

Best Answer

This question was also asked on Stack Overflow, and answered by Dan Mandle.

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