如何使用 Leaflet 更改带有缩放功能的 geojson 图标?

How change icon from geojson with zoom using Leaflet?

我无法理解这个问题。 如何使用 Leaflet 更改带有缩放功能的 geoJSON 图标? 我看过一些例子 - 。但是,它对我不起作用。这是我的代码。

<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>

也许有人知道如何解决?谢谢

您需要像下面那样修改您的 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 是一个工作示例。稍微放大地图以查看其工作情况