Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Leaflet realtime layer in a markercluster group

I'm using Leaflet in combination with the realtime and markercluster plugins in order to show markers, that get live updated on a map. The plugins work great independent from each other, but the problem arises when I want to cluster the realtime layer using the markercluster features.

Code sample for the realtime layer in which I convert the json to markers, asign a custom icon and apply some onEachFeature function:

realtimeLayer = L.realtime({
    url: 'someURL',
    crossOrigin: true,
    type: 'json'
}, {
    interval: 3 * 1000,
    onEachFeature: onEachFeature,
    pointToLayer: function(feature, latlng) {
        return L.marker(latlng, {
            icon: customIcon
        });
    }
});

What I'm able to do with non-realtime marker layers is to create a markercluster group and add the layer to it, so the markers get clustered like this:

var clusterGroup = L.markerClusterGroup();
clusterGroup.addLayer(someLayer);

However when I add the realtimeLayer to the clustergroup, the clustering is not applied, or the marker do net get loaded at all. What am I missing? Thanks!

like image 586
cf2 Avatar asked Nov 08 '22 23:11

cf2


1 Answers

You need to add the container option to your realtime object options.

From the official Leaflet Realtime documentation:

L.Realtime can also use other layer types to display the results, for example it can use a MarkerClusterGroup from Leaflet MarkerCluster: pass a LayerGroup (or any class that implements addLayer and removeLayer) to L.Realtime's container option. (This feature was added in version 2.1.0.)

  • https://github.com/perliedman/leaflet-realtime#overview

So after you initialize your cluster group and add it to map:

var clusterGroup = L.markerClusterGroup();
clusterGroup.addTo(map);

You can then pass the clusterGroup object to your realtime object in the container option:

realtimeLayer = L.realtime({
    url: 'someURL',
    crossOrigin: true,
    type: 'json'
}, {
    container: clusterGroup
    interval: 3 * 1000,
    onEachFeature: onEachFeature,
    pointToLayer: function(feature, latlng) {
        return L.marker(latlng, {
            icon: customIcon
        });
    }
});

Now when you add the realtime object to the map, it should cluster correctly:

realtimeLayer.addTo(map)

The official Leaflet Realtime repo has an example for doing what you want with the added option of grouping multiple L.Realtime objects: https://github.com/perliedman/leaflet-realtime/blob/master/examples/earthquakes.js

like image 93
max Avatar answered Nov 14 '22 21:11

max