I have been doing some mapping with Leaflet and I'm super happy with the result.
However, there is just one little thing that has been bothering me:
I have got two different circles, with popups bound to them, and depending on where I click on the circle, the popup opens in a different location...

Here is some super simple example code.
const circle = new L.circle( [52.5, 13.35] ).addTo(map);
var popup = L.popup().setContent("hello");
I have also tried var popup = L.popup().setLatLng( [52.5, 13.35] ).setContent("hello");
So is there a (preferably) easy way to make the popup box open at the middle of the circle (or have the middle of the circle as the 'anchor point'), so that where ever I click on the circle the popup always opens at the same place?
Very minor, but would appreciate any help, or directions towards a library,
Thanks!
Let me quote the Leaflet documentation about the openPopup method that every L.Layer (including every L.Circle) has:
openPopup(<LatLng> latlng?)Opens the bound popup at the specified
latlngor at the default popup anchor if nolatlngis passed.
Therefore you can:
const circle = new L.circle( [52.5, 13.35] ).bindPopup("hello").addTo(map);
circle.openPopup([52.5, 13.35]);
or
const circle = new L.circle( [52.5, 13.35] ).bindPopup("hello").addTo(map);
circle.openPopup(circle.getLatLng());
or
const circle = new L.circle( [52.5, 13.35] ).bindPopup("hello").addTo(map);
circle.on('click', function(ev) { circle.openPopup(circle.getLatLng()) });
or even
const circle = new L.circle( [52.5, 13.35] ).bindPopup("hello").addTo(map);
circle.on('click', function(ev) { ev.target.openPopup(ev.target.getLatLng()) });
See a working example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With