我在传单的地图上有一个标记:
var centerMarker = L.marker(centerPoint, { title: 'unselected' }).bindLabel(schools[i][0]);
centerMarker.on('click', selectMarker);
centerMarker.addTo(map);
我想在点击时更改该标记的大小。
我知道我们可以更改图标,但我只想更改标记的相同图标的大小。
我在传单的地图上有一个标记:
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);
});
演示(对中心和阴影等使用有些草率的设置):
虽然这是一个老问题,但如果有人正在寻找答案以外的另一种可能的选择。
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
});
}
根据@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);
});
这样您只需放大您单击的标记的图标,刷新后其他标记将保持不变。