Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

leaflet remove specific marker

I am very new to use Leaflet and its plugins. Currently I am working with a project to mark a specific location in the map with a marker.

But somehow I do not know how can I remove specific marker from the map if there are multiple markers.

Markers are bind to pop-ups with some information and a button in the box. Therefore, my aim here is to remove the specific marker after the button is clicked.

var popupContent =
    '<p>Some Infomation</p></br>' +
    '<p>' + date + '</p></br>' +
    '<button onclick=clearMarker()>Clear Marker</button>';

myMarker = L.marker([lat, lng], { icon: redMarker, draggable: false });
var myPopup = myMarker.bindPopup(popupContent, { closeButton: false });
map.addLayer(myMarker);

Please let me know if there any improvement in the way I add the markers (Pretty sure there is better way to achieve that).

like image 617
Khai Hong Avatar asked Aug 29 '17 06:08

Khai Hong


People also ask

How do you remove marker react leaflet?

You just need to filter the clicked marker' coords not to be included anymore to your state variable and that's it!

How do you delete a layer on a map in leaflet?

WMS tile layers are extensions of tile layers, so they can also be removed or cleared via removeTiles() or clearTiles() . leaflet documentation built on March 24, 2022, 1:05 a.m.

How do you add a marker in leaflet?

Adding a Simple MarkerStep 1 − Create a Map object by passing a <div> element (String or object) and map options (optional). Step 2 − Create a Layer object by passing the URL of the desired tile. Step 3 − Add the layer object to the map using the addLayer() method of the Map class.


1 Answers

Try with private properties, check on jsfiddle

var map = L.map('map').setView([51.505, -0.09], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

var markers = []

function createMarker(coords) {
  var id
  if (markers.length < 1) id = 0
  else id = markers[markers.length - 1]._id + 1
  var popupContent =
    '<p>Some Infomation</p></br>' +
    '<p>test</p></br>' +
    '<button onclick="clearMarker(' + id + ')">Clear Marker</button>';
  myMarker = L.marker(coords, {
    draggable: false
  });
  myMarker._id = id
  var myPopup = myMarker.bindPopup(popupContent, {
    closeButton: false
  });
  map.addLayer(myMarker)
  markers.push(myMarker)
}

function clearMarker(id) {
  console.log(markers)
  var new_markers = []
  markers.forEach(function(marker) {
    if (marker._id == id) map.removeLayer(marker)
    else new_markers.push(marker)
  })
  markers = new_markers
}
createMarker([51.5, -0.09])
createMarker([51.5, -0.093])
createMarker([51.5, -0.096])
like image 139
Sebastian Schulz Avatar answered Sep 22 '22 13:09

Sebastian Schulz