Reputation: 75
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!
Upvotes: 4
Views: 4959
Reputation: 19069
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
latlng
or at the default popup anchor if nolatlng
is 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.
Upvotes: 5