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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With