我当前的代码仅根据此 json 文件中的数据绑定标记:
{
"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 link = './data/events2.json' //file above
var map = L.map("mapid", {
center: [53.8460456, -38.9135742],
zoom: 12,
layers: [blueLayer, redLayer],
});
L.tileLayer(
"https://api.mapbox.com/......",
{
attribution: "......",
maxZoom: 18,
minZoom: 1,
}
).addTo(map);
function onEachFeature(feature, layer) {
return;
}
$.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);
但是,我想将标记添加到不同的图层,而不是将它们直接绑定到地图,这样我就可以执行以下操作:
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
}
}
我相信你已经快到了。在 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()
方法,除非您最初想要地图上的所有标记。希望这有帮助!