微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 检测用户启动的Panlet上的平移/缩放操作

我有一张单张地图,用于位置分享.当用户共享他们的位置时,将显示其位置的标记添加到地图中,供其他所有用户查看.每当添加,移动或删除时,它自动适应地图以显示所有标记.我还添加一个可以自动切换自适应行为的自定义控件.这一切都很好,但我也想让地图足够聪明,如果用户平移或缩放地图,自动关闭自动适应行为.

事实证明是相当困难的,因为我找不到一个好的方法来区分用户启动平移/缩放操作是否自动匹配.我最初正在听panstart和zoomstart事件,但这些也是由自动拟合触发的.我想我可以设置一个标志来告诉它,当缩放/平移是由自动拟合引起时,不要关闭自动适配.我先检查这个标志,然后关闭自动适应以响应panstart和zoomstart,然后在收到平移和缩放时清除它.

自动适应发生之前,这似乎工作正常,不会导致平移或缩放.我们假设我们有一个大的自动匹配的标记簇,其中一个标记删除.由于绑定框不变,因此不会触发平移或缩放,因此不会关闭自动适配的标志不会被清除.用户下一次平移或缩放地图时,它不会像其一样关闭自动适应,因为它认为它仍然处于自动适应操作的中间位置.

如何做到这一点,以便当用户直接放大或放大地图时,我可以可靠地关闭自动调整,但是当通过其他方式进行平移或放大时,可以将其保留下来?

以下是相关代码

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());
}

解决方法

我最后在我的fitBounds和setView调用周围设置了一个标志,例如:
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
})

不幸的是,仍然不理想,但应该做的伎俩

原文地址:https://www.jb51.cc/js/152926.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐