如何使用mapbox gl js防止鼠标滚轮交互停止fitBounds()动画?



我向地图框地图添加了一些标记,并让 fitBounds(( 方法从 geojson-extent .js调整地图位置和缩放。

map.fitBounds( geojsonExtent(geojson), {
padding: {top: 200, bottom:30, left: 30, right: 30}
});

默认情况下,动画持续时间设置为 5 秒。当用户此时在地图上执行鼠标滚轮交互时,动画将停止。没问题:缩放会停止动画。但是我怎样才能防止这种情况呢?

我尝试了很多解决方案:

1.禁用缩放

map['scrollZoom'].disable(); 

用户无法通过鼠标滚轮滚动地图,但动画仍会停止。

2. 赶上车轮事件

map.on('wheel', function(e) {
e.preventDefault();
});

用户无法通过鼠标滚轮滚动地图,但动画仍会停止。

3.完全禁用用户交互

var map = new mapboxgl.Map({
interactive: false
});

很酷,动画不再被中断,但现在用户无法平移地图。我没有找到在运行时重置此属性或添加用于平移的导航元素的解决方案。

4.将动画设置为重要

map.fitBounds( geojsonExtent(geojson), {
essential: true,
padding: {top: 200, bottom:30, left: 30, right: 30}
});

没有效果。

5.禁用动画

map.fitBounds( geojsonExtent(geojson), {
animate: false,
padding: {top: 200, bottom:30, left: 30, right: 30}
});

这有效,但这是一种解决方法。我喜欢保留动画。

6.添加叠加层以阻止用户交互

map.on('movestart', function(e){
$("#map-box").append('<div class="block-interactions"></div>');
});
map.on('moveend', function(e){
$("#map-box .block-interactions").remove();
});
.block-interactions {
position: absolute;
width: 100%;
height: 535px; /* map height */
}

这是我当前的解决方案,它有效,但感觉像一个糟糕的黑客,仍然是一种解决方法。

那么,您还有其他想法来防止动画被中断吗? 充其量使用地图框方法。

谢谢你的帮助!

您可以在调用fitBounds之前禁用交互,然后重新启用它以响应moveendzoomend事件。

// define map here...
function disableInteraction() {
map.scrollZoom.disable()
}
function enableInteraction() {
map.scrollZoom.enable()
}
map.on('moveend', function() {
enableInteraction()
})
map.on('zoomend', function() {
enableInteraction()
})
// The next two lines should go wherever you want to invoke `fitBounds`
disableInteraction()
map.fitBounds(/* ... */)

如果要禁用除滚动缩放之外的其他交互形式,可以修改disableInteractionenableInteraction。例如,要禁用所有内容:

function disableInteraction() {
map.scrollZoom.disable()
map.boxZoom.enable()
map.dragRotate.enable()
map.dragPan.enable()
map.keyboard.enable()
map.doubleClickZoom.enable()
map.touchZoomRotate.enable()
}

最新更新