【发布时间】:2023-03-13 17:26:01
【问题描述】:
我有以下代码从 API 获取一些远程 GeoJSON 并在 Leaflet 地图上显示结果:
<script>
// Center the map
var map = L.map('map').setView([54.233669, -4.406027], 6);
// Attribution
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=REMOVED', {
attribution: 'Map © <a href="https://www.openstreetmap.org/">OpenStreetMap</a>',
id: 'mapbox.streets'
}).addTo(map);
// Create an empty layergroup for the data
var LayerUTMGroundHazards = L.layerGroup();
var LayerUTMAirspace = L.layerGroup();
// Style the features
function setStyle(feature) {
return {
fillColor: feature.properties.fillColor,
color: feature.properties.strokeColor,
fillOpacity: feature.properties.fillOpacity,
opacity: feature.properties.strokeOpacity
};
}
// Build Guardian UTM
function getGuardianUTMdata() {
// Clear the current Layer content
LayerUTMGroundHazards.clearLayers();
LayerUTMAirspace.clearLayers();
// Define what we want to include
function FuncGroundHazards(feature) {
if (feature.properties.category === "groundHazard") return true
}
function FuncAirspace(feature) {
if (
(feature.properties.category === "airspace" || feature.properties.category === "airport")
&& feature.properties.detailedCategory !== "uk:frz"
) return true
}
// Build the layers
fetch("https://example.com/json?n=" + map.getBounds().getNorth() + "&e=" + map.getBounds().getEast() + "&s=" + map.getBounds().getSouth() + "&w=" + map.getBounds().getWest(), { headers: { 'Authorization': 'REMOVED', 'X-AA-DeviceId': 'mySite' } })
.then(function (responseGuardianUTM) { return responseGuardianUTM.json() })
.then(function (dataGuardianUTM) {
// Create Layer: Ground Hazards
var featuresUTMGroundHazards = L.geoJson(dataGuardianUTM, {
filter: FuncGroundHazards,
style: setStyle,
pointToLayer: function (feature, latlng) { return L.marker(latlng, { icon: L.icon({ iconUrl: feature.properties.iconUrl, iconSize: [25, 25], }), }) },
onEachFeature: function (feature, layer) { layer.bindPopup(feature.properties.name); },
});
// Add the L.GeoJSON instance to the empty layergroup
LayerUTMGroundHazards.addLayer(featuresUTMGroundHazards).addTo(map);
});
// other layers are here (removed from this example)
}
// Update the Guardian UTM layer if the map moves
map.on('dragend', function () { getGuardianUTMdata(); });
map.on('zoomend', function () { getGuardianUTMdata(); });
// Layer controls
var layerControl = new L.Control.Layers(null, {
'Airspace Restrictions': LayerUTMAirspace,
'Ground Hazards': LayerUTMGroundHazards
// other layers are here (removed from this example)
}).addTo(map);
</script>
问题是每次移动或缩放地图时,所有图层复选框都会再次重置为已检查,无论在地图移动之前检查了多少。当地图移动时,它们不会尊重/记住自己的状态。
鉴于上面的代码,我如何存储或保留我拥有的多个图层中的每一个的复选框状态,以便在每次移动地图时都不会重置它们?
编辑: 这是一个工作小提琴。从“Ground Hazards”中删除复选框,然后移动或缩放地图,您将看到它如何再次在框中打勾
【问题讨论】:
-
从表面上看,您的代码看起来不错,没有理由重置图层控件中的图层组的状态。你能创建一个jsfiddle吗?
-
嗨,我不知道我是否可以在不泄露 API 密钥和域名的情况下创建小提琴。除非有我可以使用的公共 geojson 示例?
-
也许你可以抓取一个有代表性的数据块并在小提琴中静态加载它?
-
感谢您的支持,我刚刚添加了一个工作小提琴来演示这个问题。