如何使用onEachFeature和geojson将标记添加到传单中的不同图层

时间:2017-06-07 20:35:44

标签: javascript leaflet geojson

我当前的代码只根据此json文件中的数据绑定标记

{
  "programs":{
    "undergraduate":{
      "name":"undergraduate",
      "degrees":{
        "elementary education":{
          "name":"elementary education",
          "courses":{
            "math":{
              "name":"math"
            }
          }
        }
      }
    }
  }
}

我的代码看起来像这样:

{"type": "FeatureCollection", 
    "features": [{
"geometry": {"type": "Point", "coordinates": [53.8460456,-38.9135742]},
"type": "Feature",
"properties":{"name": "red"}]}

但是,我想将标记添加到不同的图层而不是将它们全部直接绑定到地图上,所以我可以这样做:

      var blueLayer = new L.LayerGroup();
        var redLayer = new L.LayerGroup();

    var map = L.map('mapid', {
        center: [53.8460456,-38.9135742],
        zoom: 12,
        layers: [blueLayer, redLayer]
    });
    L.tileLayer('https://api.mapbox.com/styles/v1/n-alathba/cj2fzxjgl00bl2rqno6mtb9wg/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoibi1hbGF0aGJhIiwiYSI6ImNqMmZ6bTQ2cDAwNDIyeW8wY2hidjFxdjUifQ.TyQ2WNEMtCO3Q84PYXlAEA', {
        attribution: 'Tiles by <a href="http://mapc.org">MAPC</a>, Data by <a href="http://mass.gov/mgis">MassGIS</a>',
        maxZoom: 18,
        minZoom: 1,
    }).addTo(map);

 function onEachFeature(feature, layer) {
    return;
   }

 var link = './data/events2.json' //file above
 $.getJSON(link, function(events) { 
     L.geoJSON(events, {    
        style: function(feature) {
            return feature.properties && feature.properties.style;                      
       },    
     onEachFeature: onEachFeature,    
     pointToLayer: function(feature, latlng) {    
     return L.marker(latlng); }
    }).addTo(map);

1 个答案:

答案 0 :(得分:2)

我相信你快到了。在onEachFeature函数中,您只需相应地将图层添加到不同的图层组。然后,您可以随时将图层组添加到地图中。试试这个:

function onEachFeature(feature,layer) {
    if(feature.properties.name == "red") {
        // add only 'red' markers to Layer Group
        redLayer.addLayer(layer);
    } else {
        // add only 'blue' markers to Layer Group (assuming just red/blue markers)
        blueLayer.addLayer(layer);
    }
}

现在,您可以在代码中的其他位置将这些图层添加到地图中:

redLayer.addTo(mapid);
blueLayer.addTo(mapid);

除非您最初需要地图上的所有标记,否则请务必删除.addTo()后的L.geoJSON()方法。希望这有帮助!