首页 > 解决方案 > 带有轨道 fitbounds 的传单 featureGroup 无效

问题描述

有没有更好的办法???

我正在向地图添加几条轨道(使用Leaflet-gpx 插件),并希望将地图适合所有添加的轨道的边界。

通过使用 featureGroup 层来包含轨道,可以使用 fitBounds() 方法使用特征组。然而,featureGroup 没有加载事件来触发 fitBounds() 并且地图似乎也没有合适的触发器。

渲染后直接在地图上调用 fitBounds() 失败并出现“无效边界”错误。但是,将调用延迟大约一秒钟可以使其正确执行。

我认为正在发生的事情是加载组中的所有 gpx 图层需要时间,并且在完成之前,该组无法返回一组有效的边界。

因此,使用 setTimeout 来延迟 fitBounds() 可以工作,但会在地图重新渲染自身时导致一些烦人的闪烁。有没有更好的办法?

这有效:

// mapname has been created and tracks have already been loaded into their individual layers    
    var tracksLayer = L.featureGroup([track1,track2,track3]);
    tracksLayer.addTo(mapname);

//this works, with more and complex tracks you might need a longer timeout
    setTimeout(function(){ mapname.fitBounds(tracksLayer.getBounds()); }, 1000);

// this however does not work
    // mapname.on('load', function() { mapname.fitBounds(tracksLayer.getBounds());});
//nor does this despite the fact that by this stage the map has been created and the featureGroup added
    // mapname.fitBounds(tracksLayer.getBounds());

标签: javascriptleafletfitbounds

解决方案


推荐阅读