Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 582
stefcud Avatar asked Mar 20 '14 15:03

stefcud


People also ask

How do I create a pop up map in Leaflet?

Use the addPopups() function to add standalone popup to the map. A common use for popups is to have them appear when markers or shapes are clicked. Marker and shape functions in the Leaflet package take a popup argument, where you can pass in HTML to easily attach a simple popup.

How do you show markers in Leaflet?

Adding a Simple Marker Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional). Step 2 − Create a Layer object by passing the URL of the desired tile. Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

How many markers can Leaflet handle?

The Clusterer can handle 10,000 or even 50,000 markers (in chrome).


2 Answers

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 }); 
like image 198
Dan Mandle Avatar answered Sep 17 '22 20:09

Dan Mandle


Ciao Stefano,

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

i.e;

// 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!

like image 39
fitzpaddy Avatar answered Sep 16 '22 20:09

fitzpaddy