首页 > 解决方案 > 如何从单个 GeoJSON FeatureCollection 在 Leaflet 中设置多种特征类型的样式

问题描述

我在一个 FeatureCollection 中有 Point、MultiPolygon 和 Linestring 特征。我想用 circleMarker() 和其他通常的样式设置点的样式。我将点添加到 idToFeature 对象以使用 JavaScript 进行操作,但无法添加非点特征。

使用 Leaflet 1.3.3,如果我使用 pointToLayer:,点的样式很好,其他类型会渲染,默认为蓝色(不知道为什么,因为它们不是点)。我尝试使用 onEachFeature: 代替,并且可以以这种方式设置非点的样式,但不知道如何为点生成 circleMarkers。

我所拥有的 (不能设置 MultiPolygons 的样式,或者将它们添加到我的 idToFeature 对象以进行 JS 操作)

// geom is an array of features inc. Point, MultiPolygon, Linestring
renderPlaces = function(geoms) {
  data = {"type":"FeatureCollection","features":geoms}
  idToFeature = {}
  mappy.createPane('placePane');
  mappy.getPane('placePane').style.zIndex = 200;
  features = L.geoJSON(data, {
    pane: 'placePane',
    pointToLayer: function (feature, latlng) {
      identifier = feature.properties.id;
      if(feature.type=='Point'){
        marker = L.circleMarker(latlng, styles.place_default)
          .bindPopup(feature.properties.title+' (id:'+identifier+')');
        // add to array for programmatic selection
        idToFeature[identifier] = marker
        return marker
      }
    }
  }).addTo(map);
}

我尝试过的(无论如何都要一试)

features = L.geoJSON(data, {
  style: function (feature) {
    if(feature.type=="Point"){
      return {color: "#009900"};
    } else {
      return {color: "#000099"};
    }
  }
  onEachFeature: function(feature, layer) {
    if(feature.type == 'Point'){
      console.log('point', feature)
      marker = L.circleMarker(latlng, styles.place_default)
      return marker
    }
  }
}).addTo(map);

我不希望将 GeoJSON 分解为单独的特定类型的 FeatureCollections,我确信我不应该这样做......但是如何?

标签: leafletgeojson

解决方案


我拼凑了一个解决方案。它似乎并不理想,但有效:一个接一个地使用pointToLayerand onEachFeature

    features = L.geoJSON(data, {
      pointToLayer: function (feature, latlng) {
        count_features +=1;
        identifier = feature.properties.whgid;
        if(feature.type=='Point'){
          marker = L.circleMarker(latlng, styles.marker_default
          ).bindPopup(feature.properties.title+' (whg id:'+identifier+')');
          // add to array for selection
          idToFeature[identifier] = marker
          return marker
        }
      },
      onEachFeature: function(feature,layer) {
        identifier = feature.properties.whgid;
        if(feature.type != 'Point'){
          layer.setStyle(styles.default)
          idToFeature[identifier] = layer
        }
      }
    }).addTo(map);

推荐阅读