Search code examples
javascriptleafletoverpass-apileaflet.markercluster

Add markers from OverpassAPI to MarkerCluster


I have an Overpass query like this:

var opl = new L.OverPassLayer({
    query: "(node['amenity'='bench']({{bbox}});node['leisure'='picnic_table']({{bbox}}););out body;",
    markerIcon: iconn,
});
map.addLayer(opl);

But how do I take the data from this and add it to a MarkerCLuster?

Usage create a new MarkerClusterGroup example:

var markers = L.markerClusterGroup();
markers.addLayer(L.marker(getRandomLatLng(map)));
// ... Add more layers ...
map.addLayer(markers);

Solution

  • Simply add your OverPass layer to your MarkerClusterGroup:

    const markers = L.markerClusterGroup();
    markers.addLayer(opl);
    map.addLayer(markers);
    

    Note: in case the OverPass layer contains non point (~ non Markers) child layers (e.g. polygons for area features), they will still appear on the map through your MCG, but the latter will not cluster them (as it does not know which single position to use for clustering).

    Note 2: in case that OverPass layer dynamically adds more features/layers to the map (typically if it performs a new request whenever the viewport - hence its bbox - changes), the above simple scheme will not work indeed. In that case, you would probably be interested in my Leaflet.MarkerCluster.LayerSupport subplugin:

    Sub-plugin for Leaflet.markercluster plugin (MCG in short); brings compatibility with L.Control.Layers and other Leaflet plugins. I.e. everything that uses direct calls to map.addLayer and map.removeLayer.

    In your case, you should be able to use it like this:

    const mcgLayerSupportGroup = L.markerClusterGroup.layerSupport();
        
    mcgLayerSupportGroup.addTo(map);
    mcgLayerSupportGroup.checkIn(opl); // <= this is where the magic happens!
    
    opl.addTo(map);