heb*_*eba 5 javascript geojson leaflet
我当前的代码仅根据此 json 文件中的数据绑定标记:
{
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "Point",
"coordinates": [53.8460456, -38.9135742]
},
"type": "Feature",
"properties": {
"name": "red"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
我的代码看起来像这样:
const blueLayer = new L.LayerGroup();
const redLayer = new L.LayerGroup();
const link = './data/events2.json' //file above
const 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);
$.getJSON(link, (events) => {
L.geoJSON(events, {
style: (feature) => (feature.properties && feature.properties.style),
onEachFeature: onEachFeature,
pointToLayer: (feature, latlng) => marker(latlng),
});
}).addTo(map);
Run Code Online (Sandbox Code Playgroud)
但是,我想将标记添加到不同的图层,而不是将它们直接绑定到地图,这样我就可以执行以下操作:
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
}
}
Run Code Online (Sandbox Code Playgroud)
小智 3
我相信你已经快到了。在 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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以在代码中的其他位置将这些图层添加到地图中:
redLayer.addTo(map);
blueLayer.addTo(map);
Run Code Online (Sandbox Code Playgroud)
只需确保.addTo()在 后删除该方法,L.geoJSON()除非您最初想要地图上的所有标记。希望这可以帮助!