如何在地图上动态调整标记的大小

时间:2017-11-16 17:33:57

标签: maps leaflet marker

使用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的方法但是找不到让它工作的方法。 怎么做?

1 个答案:

答案 0 :(得分:0)

我最终做了什么,并且运作良好:

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