我无法理解这个问题。 如何使用Leaflet通过缩放更改geoJSON中的图标? 我看过一些例子 - Leaflet :: Changing icon based on zoom level。但是,它对我不起作用。这是我的代码。
<script>
L.mapbox.accessToken = '...';
var myMap = L.map("myMap", {
center: [47.593492, 14.529092],
zoom: 8,
minZoom: 1,
maxZoom: 10,
zoomControl: false
});
L.control.zoom({
position:'topright'
}).addTo(myMap);
L.mapbox.styleLayer('mapbox://styles/....').addTo(myMap);
var geojsonFeature = [
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [16.454314, 48.180747]
},
properties: {
title: 'Title',
description: 'Text, text...',
image: 'http://link...',
icon: {
iconUrl: 'http://link....',
iconSize: [14, 10],
iconAnchor: [0, 0],
popupAnchor: [0, 0],
className: 'dot'
}
}
},{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [16.454314, 48.180747]
},
properties: {
title: 'Title',
description: 'Text, text...',
image: 'http://link...',
icon: {
iconUrl: 'http://link....',
iconSize: [14, 10],
iconAnchor: [0, 0],
popupAnchor: [0, 0],
className: 'dot'
}
}
},{
...
}
];
function onEachFeature(feature, layer) {
var content = 'my content';
layer.bindPopup(content);
layer.setIcon(L.icon(feature.properties.icon));
}
L.geoJson(geojsonFeature, {
onEachFeature: onEachFeature
}).addTo(myMap);
var busIcon = L.icon({
iconUrl: 'http://openstationmap.org/0.2.0/client/leaflet/images/marker-icon.png',
iconSize: [23, 29],
iconAnchor: [22, 94],
popupAnchor: [-3, -76]
});
function onZoomend(feature, layer) {
var currentZoom = myMap.getZoom();
if (currentZoom > 9) {
layer.setIcon(busIcon);
}
};
myMap.on('zoomend', onZoomend);
</script>
也许有人知道如何修复它?感谢。
答案 0 :(得分:2)
您需要修改onZoomend
功能,如下所示
function onZoomend(feature, layer) {
var currentZoom = myMap.getZoom();
if (currentZoom > 9) {
geojson.eachLayer(function(layer) {
layer.setIcon(busIcon);
});
}
}
另外,将layer
保存到下面的变量
var geojson = L.geoJson(geojsonFeature, {
onEachFeature: onEachFeature,
pointToLayer: function (feature, latlng) {
return L.marker(latlng);
}
}).addTo(myMap);
Here是一个有效的例子。稍微放大地图以使其正常工作