[英]Change Leaflet marker icon with data from external geoJSON file
我在更改 Leaflet map 上的 geoJSON 数据图标时遇到问题。
我正在从外部 geoJSON 文件加载我的数据。 因此,我使用XMLHttpRequest()
打开文件(文件名存储在数组orteDB
),然后将它们添加到我的层orte
,然后将其添加到 map:
for (var i = 0; i < orteDB.length; i++) {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'files/geoJSONfiles/orte/' + orteDB[i]);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'json';
xhr.onload = function () {
if (xhr.status !== 200) return
L.geoJSON(xhr.response).addTo(orte).on('click', onClick);
};
xhr.send();
}
orte = L.geoJson(orte).addTo(map);
我已经设法借助此示例https://gist.github.com/geog4046instructor/80ee78db60862ede74eacba220809b64更改默认图标。 但我真正想要的是在单击按钮或标记本身到此redIcon
后动态更改的图标:
var redIcon = L.Icon.extend({
iconUrl: 'files/marker-icon_red.png',
iconSize: [25, 41],
iconAnchor: [12, 40],
});
我也尝试使用pointToLayer()
function 但它对我不起作用。
每个 geoJSON 点都有一个唯一的 ID,我可以通过e.layer.feature.properties.id
调用它。 所以最后我想通过使用它的唯一 ID 单独更改标记图标。
我的 geoGSON 文件如下所示:
{
"type": "FeatureCollection",
"name": "02_Roncesvalles",
"features": [
{
"type": "Feature",
"properties":
{
"id": 2 },
"geometry":
{
"type":"Point",
"coordinates": [
-1.320700314538876,
43.009378247303687 ]
}
}
]
}
非常感谢您的帮助!
您可以使用marker.setIcon(icon)
更改标记的图标,您需要遍历所有层并在 id 上找到正确的层。
我使用map.eachLayer
而不是orte.eachLayer()
因为 GeoJSON Group 也可以包含 LayerGroups。
var wantedId = 1;
map.eachLayer((layer)=>{
if(layer instanceof L.Marker && layer.feature && layer.feature.properties && layer.feature.properties.id == wantedId){
layer.setIcon(new redIcon());
}
});
更新
谢谢@ghybs,我没认出图标的extend
。
如果你想扩展图标 class 你需要将选项放在options
属性中。
var redIcon = L.Icon.extend({
options: {
iconUrl: 'files/marker-icon_red.png',
iconSize: [25, 41],
iconAnchor: [12, 40],
}
});
然后您可以使用marker.setIcon(new redIcon())
更改图标
但我建议您简单地创建一个图标变量,而不是创建一个新的 class。
var redIcon = L.icon({
iconUrl: 'files/marker-icon_red.png',
iconSize: [25, 41],
iconAnchor: [12, 40],
});
然后调用marker.setIcon(redIcon)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.