in this javascript for leaflet.js the user can keep clicking on the map to add new…
- User
in this javascript for leaflet.js the user can keep clicking on the map to add new markers. When a new marker is added I want to remove the previous marker from the map - var userMarker = L.marker(e.latlng).addTo(map); userMarkers.push(userMarker.getLatLng());
- Assistant
To remove the previous marker from the map when a new marker is added using Leaflet.js, you can use the following code:
javascript// Initialize an array to store the markers var userMarkers = []; // Event listener for when the user clicks on the map map.on('click', function(e) { // Remove previous marker from the map, if any if (userMarkers.length > 0) { var prevMarker = userMarkers.pop(); map.removeLayer(prevMarker); } // Create a new marker at the clicked location and add it to the map var userMarker = L.marker(e.latlng).addTo(map); // Store the new marker in the userMarkers array userMarkers.push(userMarker); });