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

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...