【发布时间】:2021-09-22 06:04:12
【问题描述】:
我有大约 5 个地图层作为单独的 json 文件。使用复选框单击动态获取和显示每个地图图层文件。它运行良好。我的代码如下所示。我有另一个要求将这 5 个复选框更改为单个下拉列表。当我从下拉输入字段中选择特定值时,它必须显示其相应的图层。如果我从下拉列表中选择另一个值,它必须删除先前选择的地图图层并显示新选择的值的相应图层。是否可以在下拉菜单中做同样的事情?
<div id="inputParentId" />
<input type="checkbox" id="1" onClick="togglejsonLayer(this,'lay1');" />
Layer 1
<input type="checkbox" id="2" onClick="togglejsonLayer(this,'lay2');" />
Layer 2
<input type="checkbox" id="3" onClick="togglejsonLayer(this,'lay3');" />
Layer 3
<input type="checkbox" id="4" onClick="togglejsonLayer(this,'lay4');" />
Layer 4
<input type="checkbox" id="5" onClick="togglejsonLayer(this,'lay5');" />
Layer 5
<div id="map" style="height: 600px; width: 100%;"></div>
<script>
const mbAttr = "";
const mbUrl =
"https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=xxxxxxxx";
const streets = L.tileLayer(mbUrl, {
id: "mapbox/streets-v11",
tileSize: 512,
zoomOffset: -1,
attribution: mbAttr
});
const sattelite = L.tileLayer(mbUrl, {
id: "mapbox/satellite-v9",
tileSize: 512,
zoomOffset: -1,
attribution: mbAttr
});
const map = L.map("map", {
center: [39.74739, -105],
zoom: 12,
layers: [streets]
});
var baseLayers = {
Streets: streets,
Sattelite: sattelite
};
L.control.layers(baseLayers).addTo(map);
function onEachFeature(feature, layer) {
var popupContent;
if (feature.properties && feature.properties.popupContent) {
popupContent = feature.properties.popupContent;
}
layer.bindPopup(popupContent);
}
async function getGeojson(checkbox, layerName) {
if (layers[layerName]) {
if (checkbox.checked) layers[layerName].addTo(map);
else map.removeLayer(layers[layerName]);
return;
}
const response = await fetch(`./${layerName}.json`);
const geojson = await response.json();
return geojson;
}
const layers = {};
const togglejsonLayer = async (checkbox, layerName) => {
const geojsonData = await getGeojson(checkbox, layerName);
const geojson = L.geoJSON([geojsonData], {
onEachFeature
});
const checkId = checkbox.id;
if (checkbox.checked) {
layers[layerName] = geojson;
layers[layerName].addTo(map);
} else map.removeLayer(layers[layerName]);
};
</script>
【问题讨论】:
-
所以在这种情况下,您只想在每次选择一个下拉项目时显示一个 json,而不是多个。对吗?
-
您是否尝试过查看 Leaflet 文档中的图层控件?或者您的应用程序是否需要图层选择器以不同方式工作或放置在其他位置?
-
@kboul,是的。基于从 Dropbox 中选择的值的单个 json 文件。我有一个参考。但其中所有层都在一个 json 文件中。 ahalota.github.io/Leaflet.CountrySelect/demo.html
标签: javascript jquery json leaflet maps