簡體   English   中英

更改傳單中標記的大小

[英]change size of marker in leaflet

我在傳單的地圖上有一個標記:

var centerMarker = L.marker(centerPoint, { title: 'unselected' }).bindLabel(schools[i][0]);
centerMarker.on('click', selectMarker);
centerMarker.addTo(map);

我想在點擊時更改該標記的大小。

我知道我們可以更改圖標,但我只想更改標記的相同圖標的大小。

您可以從標記本身獲取舊圖標,更改圖標的大小,然后使用更改后的圖標調用setIcon

var icon = centerMarker.options.icon;
icon.options.iconSize = [newwidth, newheight];
centerMarker.setIcon(icon);

在標記上使用setIcon ,提供具有相同圖像但不同大小和錨點的新圖標。

var centerPoint = L.latLng(55.4411764, 11.7928708);
var centerMarker = L.marker(centerPoint, { title: 'unselected' });
centerMarker.addTo(map);

centerMarker.on('click', function(e) {
    centerMarker.setIcon(bigIcon);
});

演示(使用有點草率的中心和陰影設置等):

http://jsfiddle.net/pX2xn/4/

雖然這是一個老問題,但萬一有人正在尋找除已回答的選項之外的其他可能選項。

L.marker([coord.latitude, coord.longitude], {
    color: 'red',
    icon: getIcon(), 
    data: coord
}).addTo(myMap).on("click", circleClick);

function getIcon(total_dead_and_missing) {
    var icon_size = [50, 50];   //for dynamic icon size, 
    var image_url = '1.png';        //for dynamic images

    L.icon({
        iconUrl: image_url,
        shadowUrl: 'leaf-shadow.png',

        iconSize:    icon_size , // size of the icon
        shadowSize:   [50, 64], // size of the shadow
        iconAnchor:   [22, 94], // point of the icon which will correspond to marker's location
        shadowAnchor: [4, 62],  // the same for the shadow
        popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
    });
}

資源: https : //leafletjs.com/examples/custom-icons/

根據@m13r 的建議,我發布了一個關於如何創建大尺寸圖標副本的新答案。

/// Returns a scaled copy of the marker's icon.
function scaleIconForMarker(marker, enlargeFactor) {
  const iconOptions = marker.options.icon.options;

  const newIcon = L.icon({
    iconUrl: iconOptions.iconUrl,
    iconSize: multiplyPointBy(enlargeFactor, iconOptions.iconSize),
    iconAnchor: multiplyPointBy(enlargeFactor, iconOptions.iconAnchor),
  });

  return newIcon;
}

/// Helper function, for some reason, 
/// Leaflet's Point.multiplyBy(<Number> num) function is not working for me, 
/// so I had to create my own version, lol
/// refer to https://leafletjs.com/reference.html#point-multiplyby
function multiplyPointBy(factor, originalPoint) {
  const newPoint = L.point(
    originalPoint[0] * factor,
    originalPoint[1] * factor
  );

  return newPoint;
}

用法很簡單:

  marker.on("click", function () {
    // enlarge icon of clicked marker by (2) times, other markers using the same icon won't be effected
    const largeIcon = scaleIconForMarker(marker, 2);
    marker.setIcon(largeIcon);

  });

這樣您只需放大您單擊的標記的圖標,刷新后其他標記將保持不變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM