Search code examples
leafletsetintervalgeojsonmarkerclustererleaflet.markercluster

Refreshing leaflet marker cluster data, not the whole page


I am trying to load my leaflet markercluster data in every one minute. For that I was using pythonscript which generates a geojson file in every minutes. Then i created marker cluster and tried to load that in every minutes by using setInterval. While trying that, it appears like the new geojson appends to the previous one, But i just want to show the latest one.

The result i have got

The code i using is...

 setInterval(function() {
$.getJSON("gdf1000_rand_tallinn_auto_try.geojson",function(data){

var tallinn_data = L.geoJson(data,{
  pointToLayer: function(feature,latlng){
    var marker = L.marker(latlng);
    marker.bindPopup(feature.properties.lat);
    return marker;
  }
});
var clusters = L.markerClusterGroup();
clusters.addLayer(tallinn_data);
map.addLayer(clusters);
  });
   }, 60000);

Solution

  • If the problem is what you described, then you need a conditional statement which checks if the layer has already existed or not.

    Please see below the example of a code solving this problem:

    var geojson = L.geoJSON;
    
    $.getJSON("grid_points", function(data) {
       if (map.hasLayer(geojson)){
             map.removeLayer(geojson); 
                }
       geojson=L.geoJSON(data, {
               style: positium_style
                })
      map.addLayer(geojson);
    });