1

I am trying to display a polygon from an external geojson file, the data loads but does not update the polygon in real time.

The polygon is added but color is not updated after interval when level changes.

Heres is my code:

L.realtime({
 url: 'js/areas.json',
 crossOrigin: true,
 type: 'json'
}, {
interval: 60 * 1000,
onEachFeature: function (feature, latlng) {

 var level = feature.properties.level;

 if (level == 0) {

 var polygon = L.polygon(latlng._latlngs, {
   color: '#51F03B',
   opacity: 0.3,
   fillOpacity: 0.1
 }).addTo(map);
} else if (level == 1) {

var polygon = L.polygon(latlng._latlngs, {
  color: '#F43B19',
  opacity: 0.3,
  fillOpacity: 0.1
 }).addTo(map);
}
return polygon;
},
updateFeature: function (feature, oldLayer, newLayer) {

 var level = feature.properties.level;
 if (!oldLayer) {
 return;
 }

 if (level== 0) {
  oldLayer.setStyle({color: '#51F03B'});
 } else if (level == 1) {
  oldLayer.setStyle({color: '#F43B19'});
 }
 return oldLayer;
 }
});

If i don´t return oldLayer, the polygon color changes but don´t remove the previous polygon.

geoJson file:

{
"type": "FeatureCollection",
"features": [{
    "type": "Feature",
    "properties": {
        "level": 0,
        "id": 1
    },
    "geometry": {
        "type": "Polygon",
        "coordinates": [[
            [-75.360297, 6.071571],
            [-76.005083, 6.063846],
            [-76.051694, 6.511708],
            [-75.298149, 6.573451]
        ]]
    }
}]
}

I show markers and more in this way but I don't know if being polygons is different.

DevKer
  • 15
  • 1
  • 7

1 Answers1

1

The way I worked with "real-time" with polygon was cleaning the previous polygon and creating a new one. With that in mind, you will need to keep track of the layers that you have created (like in an array), a method to clear that layer (or clear all layers, there's a leaflet method for that) and a method to set a timeOut to call an update method.

I say "real-time" because currently, I keep asking back-end for an update using a timeOut function.

first, when you received the geojson draw the polygon, add it to your map and call the setTimeout with your update method.

second, you will need a method to remove the old layer, something like this:

const resetPolygonArray = polygonId => { 
    myPolygon = polygonArray.filter(polygon => {
        if (polygon.id != polygonId) {
            return myPolygon
        } else {
        map_machiney.removeLayer(myPolygon.geojson)
        }
    })
}

even though you can use that array to store the polygon and the marker related to it, like this structure:

polygonArray.push({
    id: polygonId,
    geojson: geojson,
    marker: marker
})
Jafi
  • 19
  • 4