Reputation: 89
Attempting to draw a circle around a location on a map using a javascript listener. The map is rendered using leaflet js. This code works, but only when clicking on the map layer and not the markers. Is there a way for it to listen to marker on click
as well and draw a circle around it?
// Declare a global variable to store the circle layer
var clickCircle;
// Disable the default double-click zoom behavior
map.doubleClickZoom.disable();
// Add a click event listener to the map
map.on('click', function(e) {
// If the circle layer already exists, remove it from the map
if (clickCircle) {
map.removeLayer(clickCircle);
}
// Create a new circle layer using the latitude and longitude of the click event
clickCircle = L.circle(e.latlng, {
color: 'steelblue',
fillColor: 'steelblue',
fillOpacity: 0.5,
radius: 4023
}).addTo(map);
});
Upvotes: 0
Views: 535
Reputation: 11338
Yes you can add a click listener to a marker and then get the latlng from the marker:
marker.on('click', (e)=>{
var markerLayer = e.target;
// If the circle layer already exists, remove it from the map
if (clickCircle) {
map.removeLayer(clickCircle);
}
// Create a new circle layer using the latitude and longitude of the click event
clickCircle = L.circle(markerLayer.getLatLng(), {
color: 'steelblue',
fillColor: 'steelblue',
fillOpacity: 0.5,
radius: 4023
}).addTo(map);
});
Upvotes: 1