2

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?

2
  • Could you add a sample of your GeoJSON?
    – iH8
    Commented Mar 7, 2015 at 12:37
  • Sure, here it is: '{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[23.588973,46.772968]},"properties":{"id":198,"mynumber":"195","status":"RED"}}]}'
    – Flaviu
    Commented Mar 7, 2015 at 12:46

1 Answer 1

4

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

1
  • You're right, it works, but I had to declare a function for this, here is the code: realtime.on('update', function(e) { updateFeatureIcon = function (fId) { var feature = e.features[fId], mynumber = feature.properties.mynumber; status = feature.properties.status; realtime.getLayer(fId).setIcon(new L.AwesomeNumberMarkers({ number: mynumber, markerColor: status.toLowerCase() })); }; Object.keys(e.update).forEach(updateFeatureIcon); });
    – Flaviu
    Commented Mar 8, 2015 at 11:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.