地图缩放时调整 Leaflet 自定义图标大小。性能图标 vs DivIcon

6
我试图在leaflet缩放时调整自定义图标的大小。我提出了两个解决方案,一个使用L.Icon标签,另一个使用L.divIcon。在这两个示例中,我只设置了1个标记和分组以提高可读性。 方法1使用L.Icon:使用标记创建分组。然后在zoomend上使用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>

方法2使用L.divIcon:我创建图标和不同的组,并为每个图标添加一些CSS样式,使用background-image属性。然后,在zoomend事件上,我仅使用JQuery更改CSS样式。background-size CSS属性允许我更改图像大小。我对每个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/...方面的经验。
第二个选项是否更可取,因为它不需要重新设置每个图标?当有大量组/图标时,这样做是否会提高性能?
1个回答

11

我使用 performance.now() 进行了一次测试。我在一个 1024x1180(边界)的自定义地图上进行了测试。一次使用 676 个标记,然后减少到大约一半,最后只使用 100 个标记。性能是在 map.on('zoomend', function() { 函数内测量的。

  • 使用 676 个标记时,L.Icon 方法更新需要 2500-2900 毫秒,而 L.divIcon 只需要 10-30 毫秒。
  • 标记数量减半也将此时间减半。
  • 对于大约 100 个标记(104),L.Icon 更新需要 300-400 毫秒。相比之下,L.divIcon 只需要 4-5 毫秒。

我还计算了初始化(L.layerGroup([...]).addTo(map))使用 676 个标记的性能。 L.Icon 需要 2200-2400 毫秒,而 L.divIcon 只需要 80-95 毫秒。

L.divIcon 显然表现更好(如预期)。虽然这有点像欺骗,但我认为我更喜欢使用这种方法。如果我们想要缩放,我无法直接想到为什么会更喜欢使用 L.Icon 方法。

编辑: 我注意到根据Leaflet 文档 'Icon',您还可以向图标分配 className。使用 css 属性 widthheight 可以像之前对 divIcons 所做的那样完成相同的操作,从而省去了大量加载时间,但仍允许您使用与L.Icon 链接的所有选项。您的初始化时间仍然会更长。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接