I'm using the open source Leaflet.js library to create a simple map.
I'm trying to solve a specific problem though. Markers are tied to a specific lat/lng on a map, which makes sense, but I need to be able to make a marker have a fixed offset position from another marker, without it being tied to a lat/lng center.
So for example, the map may look like this:
But when you zoom out, it'll look like this:
What I actually want is for the right marker to be a fixed offset away from the left marker, instead of being tied to a latlng, as such:
I've tried experimenting with unproject but I believe I'm going down the wrong path of how to handle this. It's unconventional what I'm doing but if anyone has any insight into how I could do this, it would be greatly appreciated.
This sounds like an XY problem to me: you want to display some extra info (possibly looking similar to a normal Marker) next to a Marker A (with some pixels offset), and you try with another Marker B; but Marker B is tied to Lat/Lng coordinates instead of pixels offset, so you ask for help on how to use
unproject
.To achieve your original objective, a Leaflet DivIcon would indeed have been a more appropriate solution: a part of the
<div>
would contain your actual Marker Icon, and another part would contain your extra info. That way, it always stays at the desired position, without having to compute any (un)projection and without any JS event listener involved:An even more appropriate solution would have been to use a Leaflet Tooltip, typically with your predefined
offset
,permanent: true
option, a specificdirection
and custom styling (withclassName
):Then if you really want your extra info to be styled and manipulated like a normal Leaflet Marker, another possible solution would be to use a custom Marker with modified
iconAnchor
, to account for your desired pixel offset:In addition to
project()
andunproject()
methods to calculate position of second marker you can also listen to zoom events on the map and update the position of the second marker in order to keep the desired distance in pixels.Have a look at the following example.
I hope this helps!