1

I'm working on a SvelteKit project where we're moving from Google Maps to Open Street Maps using Leaflet.js. With Google Maps we have a marker that always stays in the center of the map even when panning around.

I want to do the same thing with Leaflet. But the marker always stays on the default location on the map.

I currently have the marker defined as such

currentPositionMarker = new L.marker(map.getCenter(), {
  icon: icon // icon is defined earlier in the code
}).addTo(map)

...

function centerMarkerOnMap(map) {
  currentPositionMarker.setLatLng(map.getCenter())
}

...

map.on('moveend', centerMarkerOnMap)

Currently I get Uncaught TypeError: map.getCenter is not a function in the console. I'm not sure why, since I'm using map.getCenter() to set the original marker position with no issues.

I'm open to any and all suggestions. Thanks in advance.

1 Answer 1

0

You get this error because the parameter passed to the function is a LeafletEvent.

The map object is available in event.target:

function centerMarkerOnMap(event) {
  currentPositionMarker.setLatLng(event.target.getCenter())
}

map.on('moveend', centerMarkerOnMap)

I've prepared a demo where the marker always stays in the center of the map:

https://stackblitz.com/edit/marker-always-ceter?file=index.js

Not the answer you're looking for? Browse other questions tagged or ask your own question.