0

I try to center a map on the active marker with Leaflet (version 1.7.1). For that, when I create a marker, I add an event:

function addMarkerTomap(map) {
...
var result = L.marker(lat,lng],{icon:myIcon}.addTo(map).on(`click', centerMap);
...
}

Note that map is a parameter, not a global variable. Now I define the centerMap function:

function centerMap(e) {
   map.panTo(e.LatLng);
}

As you guess, map is undefined in centerMap. I tried that:

var result = L.marker(lat,lng],{icon:myIcon}.addTo(map).on(`click', centerMap(map));

and

function centerMap(map,e) {
   map.panTo(e.LatLng);
}

But that doesn't work ! Any idea how to call the function with a parameter ?

Thank you by advance,

Note 1: If I do:

function addMarkerTomap(map) {
...
var result = L.marker(lat,lng],{icon:myIcon}.addTo(map).on('click', function(e){map.panTo(e.LatLng);});
...
}

That doesn't work !

Note 2: if I do:

map.panTo(e.latlng)

click on the marker: the popup window is displayed but the map is not centered, a second click and the map is centered but the popup is closed !
Probably because the click cannot opend the popup AND execute the panTo in same time.

Note 3: I tried to center the map when the popup is open:

result.binPopup(popup,options).on('popupopen',function(popup){map.panTo(popup.getLatLng);});

That also doesn't work !

jpc
  • 5
  • 3
  • So `.on('click', centerMap);` would be correct but be sure that you use `'` . Also the property of the event is lowercase: `map.panTo(e.latlng);` – Falke Design Feb 26 '21 at 13:03
  • yes, that was a typo fault ! but that doesn't work – jpc Feb 26 '21 at 13:16

0 Answers0