javascript - 如何使用 Leaflet 通过缩放更改 geojson 中的图标?

标签 javascript leaflet zooming

我无法理解这个问题。 如何使用 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>

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

最佳答案

您需要修改您的 onZoomend 函数,如下所示

function onZoomend(feature, layer) {
    var currentZoom = myMap.getZoom();
      if (currentZoom > 9) {
        geojson.eachLayer(function(layer) {
          layer.setIcon(busIcon);
        });
      } 
}

此外,将您的图层保存到变量中,如下所示

var geojson = L.geoJson(geojsonFeature, {
    onEachFeature: onEachFeature,
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng);
    }
}).addTo(myMap);

Here是一个工作示例。放大 map 看看它的工作情况

关于javascript - 如何使用 Leaflet 通过缩放更改 geojson 中的图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41534115/

相关文章:

javascript - 如何找到 DIVS 的 ID,并将这些名称作为类分配给其他 DIVS?

reactjs - 在传单矩形内添加文本

使用 rCharts 和 shiny 删除传单热图层

html - iOS 双击缩小,即使 user-scalable=no

android - 如何在多点触控上缩放整个 Activity ?

javascript - 缩放 css/javascript

javascript - 使用 AJAX 更新返回错误并直接转到路由显示 "MethodNotAllowedHttpException No message"

javascript - 无法缩放 UIWebView

javascript - 带有 grunt 的动态数据表

css - 将 Leaflet divIcon 标记与动态内容居中