Search code examples
javascriptreal-timeleafletgeojson

Leaflet Realtime GeoJSON dynamic marker color change


I have a map built with Leaflet which displays markers from a GeoJSON using Leaflet-Realtime plugin and Leaflet-awesome-numbered-marker plugin. However I noticed that the markers color doesn't change dynamically, but it changes if I reload the page. Here's the code so far:

var map = L.map('map', {center: [46.7634, 23.5996], zoom: 14}),
realtime = L.realtime({
    url: 'get_markers.php',
    crossOrigin: true,
    type: 'json'
}, {
    interval: 500,

    pointToLayer: function (feature, latlng) {
    return L.marker(latlng, {
        'icon': new L.AwesomeNumberMarkers({
                  number: feature.properties.mynumber, 
                  markerColor: feature.properties.status.toLowerCase()
              })

    });
}
}).addTo(map);

In feature.properties.status is the color code for my markers. I want to change the color of the marker in realtime according to the property in json. Any ideas?


Solution

  • You can use the updateFeature option of L.Realtime. It takes a method with three parameters: feature, oldLayer and newLayer. In there just take the newLayer and use the setIcon method of the marker:

    updateFeature: function (feature, oldLayer, newLayer) {
        newLayer.setIcon(new L.AwesomeNumberMarkers({
            number: feature.properties.mynumber, 
            markerColor: feature.properties.status.toLowerCase()
        }));
    }
    

    Unable to test, but that should work.

    Reference: https://github.com/perliedman/leaflet-realtime#-options