How to add markers to different layers in leaflet using onEachFeature and geojson

和自甴很熟 提交于 2019-12-23 12:18:27

问题


My current code merely binds markers according to the data from this json file

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

and my code looks something like this:

      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);

However, I would like to add markers to different layers instead of binding them all directly to the map so I can do something like this:

function onEachFeature(feature,layer){
      if(feature.properties.name == "red"){ //do something that binds associated marker to red layer)
       else{//do something that binds associated marker to bluelayer}}

回答1:


I believe you are nearly there. In your onEachFeature function, you can simply add layers to your different Layer Groups accordingly. Then, you can add the Layer Groups to the map whenever you want. Try this out:

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);
    }
}

Now somewhere else in your code you can add these layers to your map:

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

Just make sure to remove the .addTo() method after the L.geoJSON() unless you want all the markers on the map initially. Hope this helps!



来源:https://stackoverflow.com/questions/44422287/how-to-add-markers-to-different-layers-in-leaflet-using-oneachfeature-and-geojso

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!