我试图在放大传单时调整自定义图标的大小。我为此想出了两种解决方案。一个使用L.Icon
标签,另一个使用L.divIcon
。在这两个示例中,为了便于阅读,我仅设置了 1 个标记和组
Method 1 using L.Icon:用标记进行分组。然后在zoomend
i use mygroup.eachLayer(function (layer)
使用以下命令更改 1 层的所有图标layer.setIcon()
。我对所有小组重复这一点
<script>
// Setting map options
....
// Setting Icon
var normalicon = L.icon({
iconUrl: 'icon1.jpg',
iconSize: [40,40],
iconAnchor: [20,20],
popupAnchor: [0,-20]
});
// Create a group
var normalLayer = L.layerGroup([
L.marker([200,200], {icon:normalicon})
]).addTo(map);
// Resizing on zoom
map.on('zoomend', function() {
// Normal icons
var normaliconresized = L.Icon.extend({
options: {
iconSize: [20*(map.getZoom()+2), 20*(map.getZoom()+2)], // New size!
iconAnchor: [20,20],
popupAnchor: [0,-20]
}
});
var normaliconchange = new normaliconresized({iconUrl: 'icon1.jpg'})
normalLayer.eachLayer(function (layer) {
layer.setIcon(normaliconchange);
});
.... Do the same for the other groups
});
</script>
Method 2 using L.divIcon:我制作图标和不同的组,并为每个图标添加一些 CSSbackground-image
财产。然后在zoomend
我只是使用 JQuery 来更改 css。background-size
css-property 允许我更改图像大小。我为每个 divIcon 类执行此操作
Css
.iconsdiv{
width:20px; height:20px;
background-image:url("icon2.jpg");
background-size: 20px 20px;
}
Script
<script>
// Setting map options
....
// Setting Icon
var divicon = L.divIcon({className: 'iconsdiv', iconSize: null }); // Explicitly set to null or you will default to 12x12
// Create a group
var divLayer = L.layerGroup([
L.marker([200,200], {icon:divicon})
]).addTo(map);
// Resizing on zoom
map.on('zoomend', function() {
var newzoom = '' + (20*(map.getZoom()+2)) +'px';
$('#map .iconsdiv').css({'width':newzoom,'height':newzoom,'background-size':newzoom + ' ' + newzoom});
... repeat for the other classes
});
</script>
我几乎没有任何关于 javascript/jquery/... 的经验
第二个选项是否更好,因为它不需要重新设置每个图标?当有大量组/图标时,它会提高性能吗?