我正在尝试更改其中一个 KML 图层的默认标记。为此,我正在使用 leaflet-omnivore。
这是我已有的代码。标记未更改为图像,图层控件仅显示文本,即使 img 位在代码中也是如此。
标记代码:
var redIcon = L.icon({
iconUrl: 'icon.png',
iconSize: [20, 24],
iconAnchor: [12, 55],
popupAnchor: [-3, -76]
});
var nissanLayer = omnivore.kml('icons.kml')
.on('ready', function() {
map.fitBounds(customLayer.getBounds());
//change the icons for each point on the map
// After the 'ready' event fires, the GeoJSON contents are accessible
// and you can iterate through layers to bind custom popups.
customLayer.eachLayer(function(layer) {
// See the `.bindPopup` documentation for full details. This
// dataset has a property called `name`: your dataset might not,
// so inspect it and customize to taste.
layer.icon
layer.bindPopup('<img src="icon.png" height="24"><br><h3>'+layer.feature.properties.name+'</h3>');
});
})
.addTo(map);
var marker = new L.Marker(customLayer, {icon:redIcon});
map.addLayer(marker);
最佳答案
你好像忽略了setIcon()
method of L.Marker
.在调用任何 L.Marker
功能之前,我还会检查 L.Layer
实际上是 L.Marker
,只是为了代码完整性.例如:
var redIcon = L.icon({ /* ... */ });
var omnivoreLayer = omnivore.kml('icons.kml')
.on('ready', function() {
omnivoreLayer.eachLayer(function(layer) {
if (layer instanceof L.Marker) {
layer.setIcon(redIcon);
}
});
})
.addTo(map);
然而,Leaflet-Omnivore documentation表示将自定义样式应用于 Omnivore 层的更好方法是创建一个具有所需过滤器和样式的 L.GeoJSON
实例,然后将其传递给 Omnivore 工厂方法。我建议你阅读 Leaflet tutorial on GeoJSON熟悉这一点。
因此,与其依赖 on('ready')
事件处理程序(这会在标记创建后更改),这会节省一点点通过直接使用所需样式创建标记来节省时间:
var omnivoreStyleHelper = L.geoJSON(null, {
pointToLayer: function (feature, latlng) {
return L.marker(latlng, {icon: redIcon});
}
});
var omnivoreLayer = omnivore.kml('icons.kml', null, omnivoreStyleHelper);
关于javascript - 如何在传单杂食层上使用自定义图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50624063/