简体   繁体   中英

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:

以传单地图为中心的弹出窗口

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

Ciao Stefano,

This is untested pseudocode, but Leaflet project/unproject functions should provide assistance.

ie;

// Obtain latlng from mouse event
var latlng;
// Convert latlng to pixels
var px = project(latlng);
// Add pixel height offset to converted pixels (screen origin is top left)
px.y -= mypopup.height/2
// Convert back to coordinates
latlng = unproject(px);
// Pan map
map.panTo(latlng,{animate: true});

This depends on zoom scale being constant during calculation, so you might be required to pan the map and then calculate the pan offset to update correctly (using animation , this will only be a gentle transition).

Good luck!

Here's an easy solution:

First you center the map to your marker.

map.setView(marker.latLng);

Then you open the popup.

var popup.openOn(map); = L.popup()
    .setLatLng(marker.latLng)
    .setContent(dynamic-content)
    .openOn(map);

Leaflet will automatically pan the map so the popup fits on the map. To make it look more beautiful you can add a margin-top to the popup with CSS.

My very simple solution keeps the current zoom level as well for better usability.

map.on('popupopen', function (e) {
    map.setView(e.target._popup._latlng, e.target._zoom);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM