Search code examples
javascriptleafletgeojson

Leaflet Multiple geoJSON Layer Clustering and Layer Controlling


I want to implement marker clustering for multiple geoJSON layers. After some research, using Leaflet.FeatureGroup.SubGroup plugin looks like the solution I need.

How can I iterate over the geoJSON to dynamically add/remove Layer Groups from the map with current code sample I have provided?

addGeoJsonLayers: =>
    L.mapbox.accessToken = MAP_BOX_ACCESS_TOKEN

    streetsLayer = L.mapbox.tileLayer('mapbox.streets')
    streetsLayer.on 'ready', => streetsLayer.addTo(@map)

    baseLayers =
      'Road': streetsLayer
      'Terrain': L.mapbox.tileLayer('mapbox.outdoors')
      'Satellite': L.mapbox.tileLayer('mapbox.satellite')

    geojsonLayers = {}

    @shares.forEach (share, index) =>
      titleLabel = CommunityMap.labelForDataId(share.schema.elements, share.schema.record_title_key)
      geojsonOptions = {
        onEachFeature: (feature, layer) =>
          record = new CommunityGeoJSONRecord(properties: feature.properties, titleLabel: titleLabel)

          @records[record.id] = { record: record, layer: layer }

          layer.bindPopup record.contentForPopUp()

        pointToLayer: (feature, latLng) ->
          if share.status_enabled
            color = feature.properties['marker-color'] || INVALID_STATUS_MARKER_COLOR
          else
            color = MARKER_COLORS[index]
          L.marker([latLng.lat, latLng.lng], {
            icon: L.mapbox.marker.icon({
              'marker-size': 'small'
              'marker-color': color
            })
          })
      }

      share.geojsonLayer = L.geoJson(null, geojsonOptions).addTo(@map)

      geojsonLayers[share.name] = share.geojsonLayer

      $.getJSON "#{share.url}?human_friendly=1", (data) =>
        @loadData(data, share.geojsonLayer, titleLabel)

    L.control.zoom(position: 'topright').addTo(@map)

    L.control.layers(baseLayers, geojsonLayers, position: 'topright').addTo(@map)

Solution

  • Something like that should work:

    var mcg = L.markerClusterGroup().addTo(@map);
    
    // within your @shares loop…
    
      share.subGroupLayer = L.featureGroup.subGroup(mcg).addTo(@map);
    
      // Do not add directly to map, but to the intermediate subGroup instead!
      share.geojsonLayer = L.geoJSON(null, geojsonOptions).addTo(share.subGroupLayer);
    
      geojsonLayers[share.name] = share.subGroupLayer; // use the subgroup instead.