deleting Leaflet realtime markers

2019-02-20 22:21发布

问题:

I have a leaflet map that tracks realtime data and i currently have it updating the positions correctly every x seconds, but the old markers are not being deleted. Im at the point that I will just remove all markers and re-add them. I think this is also impacting memory for the page, because the values increase by 166 every time

I have to be overlooking something really silly.

My json is like:

{"_items": [{"uniqueID": "a123", "isMoving": false, "bearing": 231, "longitude": -xx.xxxxx, "latitude": xx.xxxxx}]}

And here is the code that adds the markers

var marker = new Array();
for(i=0;i<myjson._items.length;i++){
    var LamMarker = new L.marker([myjson._items[i].latitude, myjson._items[i].longitude],{
       icon: autotop
    });
    console.log(myjson._items[i].latitude)
    marker.push(LamMarker);
    map.addLayer(marker[i]);
    }
}

i have been trying something along the lines of

if (map.hasLayer(marker)) {
  for(i=0;i<marker.length;i++) {
map.removeLayer(marker[i])
   }
  }

before my function fires.

Any help would be great.

回答1:

An extremely simple way of deleting all your markers is to use an intermediary Layer Group: instead of adding your Markers directly to your map, add the group to the map, and your Markers into the group. Then remove all its child Markers with its clearLayers() method:

Removes all the layers from the group.

var map = L.map("map").setView([48.86, 2.35], 11);

var layerGroup = L.layerGroup().addTo(map);

function refreshMarkers() {
  layerGroup.clearLayers();
  for (var i = 0; i < 10; i += 1) {
    L.marker(getRandomLatLng()).addTo(layerGroup);
  }
}

setInterval(refreshMarkers, 2000);

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

function getRandomLatLng() {
  return [
    48.8 + 0.1 * Math.random(),
    2.25 + 0.2 * Math.random()
  ];
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script>

<div id="map" style="height: 180px"></div>