【问题标题】:how to resize dynamically markers on a map如何在地图上动态调整标记的大小
【发布时间】:2017-11-16 17:33:56
【问题描述】:

我的 Leaflet.js 练习:通过修改 iconSize 选项(即不通过更改图标源)放大或缩小时调整标记图标的大小。

我试过这个:

function resize(e) {

  for (const marker of markers) {

    const newY = marker.options.icon.options.iconSize.y * (mymap.getZoom() / parameterInitZoom);
    const newX = marker.options.icon.options.iconSize.x * (mymap.getZoom() / parameterInitZoom);

    marker.setIcon(marker.options.icon.options.iconsize = [newX, newY]);
  }
}

mymap.on('zoomend', resize)

但我最终得到了: t.icon.createIcon is not a function

我也看到了 muliplyBy 方法,但找不到让它工作的方法。 怎么办?

【问题讨论】:

    标签: maps leaflet marker


    【解决方案1】:

    我最后做了什么,效果很好:

    let factor;
    let markers = [];
    
    
    //New class of icons
    const MyIcon = L.Icon.extend({
      options: {
        iconSize: new L.Point(iconInitWidth, iconInitHeight) //Define your iconInitWidth and iconInitHeight before
      },
    });
    
    /*------------ Functions - Callbacks ----------------*/
    //Small function to keep the factor up to date with the current zoom
    function updateFactor() {
      let currentZoom = mymap.getZoom();
      factor = Math.pow(currentZoom / mymap.options.zoom, 5);
    };
    updateFactor();
    
    //Create a new marker
    function makeMarker(e) {
      const newX = Math.round(iconInitWidth * factor);
      const newY = newX * iconInitHeight / iconInitWidth;
    
      const newMarker = new L.Marker(new L.LatLng(e.latlng.lat, e.latlng.lng), {
        icon: new MyIcon({ iconSize: new L.Point(newX, newY) })
      }).addTo(mymap);
    
      markers[markers.length] = newMarker;
    }
    
    //Update the marker
    function resize(e) {
      updateFactor();
    
      for (const marker of markers) {
    
        const newX = Math.round(iconInitWidth * factor);
        const newY = newX * iconInitHeight / iconInitWidth;
    
        marker.setIcon(new MyIcon({ iconSize: new L.Point(newX, newY) }));
      }
    }
    
    /*------------ Event listeners ----------------*/
    mymap.addEventListener('click', makeMarker);
    mymap.on('zoom', resize);
    

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多