Leaflet Multiple geoJSON Layer Clustering and Layer Controlling

时间:2017-05-08 20:57:28

标签: javascript leaflet geojson

我想为多个geoJSON图层实现标记聚类。经过一些研究,使用Leaflet.FeatureGroup.SubGroup插件看起来就像我需要的解决方案。

如何迭代geoJSON以使用我提供的当前代码示例从地图中动态添加/删除图层组?

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)

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

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.