gpt4 book ai didi

javascript - 在 Leaflet 上检测用户发起的平移/缩放操作

转载 作者:可可西里 更新时间:2023-11-01 01:34:45 25 4
gpt4 key购买 nike

我有一个用于位置共享的传单 map 。当用户分享他们的位置时,显示他们位置的标记将添加到 map 上,供所有其他用户查看。无论何时添加、移动或删除标记,它都会自动调整 map 以显示所有标记。我还添加了一个自定义控件,可以打开和关闭自动调整行为。这一切都很好,但我还想让 map 足够智能,以便在用户平移或缩放 map 时自动关闭自动调整行为。

事实证明这非常困难,因为我找不到区分平移/缩放操作是由用户启动还是由自动调整启动的好方法。我最初是在监听 panstart 和 zoomstart 事件,但这些事件也是由自动调整触发的。我想我可以设置一个标志来告诉它在缩放/平移是由自动调整引起时不要关闭自动调整。在响应 panstart 和 zoomstart 关闭自动调整之前,我首先检查这个标志,然后在收到 panend 和 zoomend 时清除它。

在发生不会导致平移或缩放的自动调整之前,这似乎工作正常。假设我们有一大群 Autowiring 的标记,中间的一个标记被移除。由于绑定(bind)框未更改,因此不会触发平移或缩放,因此告诉它不要关闭自动调整的标志永远不会被清除。下次用户平移或缩放 map 时,它不会像应有的那样关闭自动调整,因为它认为它仍处于自动调整操作的中间。

如何才能在用户直接平移或缩放 map 时可靠地关闭自动调整,而在通过其他方式平移或缩放 map 时保持打开状态?

相关代码如下:

var markers = [];        // Map markers are stored in this array.
var autoFit = true; // Whether auto-fit is turned on
var lockAutoFit = false; // Temporarily lock auto-fit if true
var map; // Leaflet map object

function initMap() {
// Leaflet map initialized here
map.on('movestart zoomstart', function() {
if (!lockAutoFit) {
autoFit = false;
}
});
map.on('moveend zoomend', function() {
lockAutoFit = false;
});
}

function toggleAutoFit() {
autoFit = !autoFit;

if (autoFit) {
lockAutoFit = true;
fitMap();
}
}

function addOrUpdateMarker(marker, coords) {
lockAutoFit = true;
// do the marker update here
fitMap();
}

function removeMarker(marker) {
lockAutoFit = true;
// remove the marker here
fitMap();
}

// Pans and zooms the map so that all markers fit in the map view.
// Invoked whenever a marker is added, moved or deleted, or when
// the user turns on auto-fit.
function fitMap() {
if (!autoFit || !markers.length) {
return;
}

map.fitBounds(new L.featureGroup(markers).getBounds());
}

最佳答案

我最终在我的 fitBoundssetView 调用周围设置了一个标志,例如:

isProgramaticZoom = true
map.fitBounds(new L.featureGroup(markers).getBounds());
isProgramaticZoom = false

然后是关闭自动适应的代码:

map.on('zoomstart', function() {
if (!isProgramaticZoom) {
//turn off auto-fit
}
})

map.on('dragstart', function() {
//turn off auto-fit
})

不幸的是,仍然不理想,但应该可以解决问题

关于javascript - 在 Leaflet 上检测用户发起的平移/缩放操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31992278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com