每当用户与地图交互时如何执行一些代码? [英] How to execute some code whenever the user interacts with the map?

查看:50
本文介绍了每当用户与地图交互时如何执行一些代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 OpenLayers 3.9.0 地图.我还有一对 LonLat 坐标,我正在从外部源跟踪并更新到地图上.我不断地将地图重新​​集中在这些坐标上:

I have an OpenLayers 3.9.0 map. I also have a pair of LonLat coordinates that I am tracking from an external source and updating onto the map. I am continuously re-centering the map on these coordinates:

function gets_called_when_I_have_updated_coords() {
    map.getView.setCenter(coords);
}

我想要的是在用户与地图交互时禁用此自动居中.换句话说,我想要这个:

What I want is to disable this auto-centering whenever the user interacts with the map. In other words, I want this:

var auto_center = true;

function gets_called_when_I_have_updated_coords() {
    if (auto_center) {
        map.getView.setCenter(coords);
    }
}

function user_started_interacting() {
    auto_center = false;
}
// But where should this function be attached to?
// where.on('what?', user_started_interacting);

我不知道如何检测用户交互.

I don't know how to detect a user interaction.

我希望 默认交互某种事件,以便当用户开始拖动/旋转/缩放地图时,将触发一个事件并运行我的代码.我找不到这样的事件.

I expected that the default interactions had some kind of event, so that when the user starts dragging/rotating/zooming the map, an event would be triggered and my code would run. I could not find such event.

推荐答案

作为一种解决方法,我可以将事件附加到视图中的更改:

As an workaround, I can attach an event to a change in the view:

map.getView().on('change:center', function(ev){…});

但是我必须采取额外的步骤来区分代码启动的更改和用户启动的更改.完整的代码看起来有点像这样:

But I must take extra steps to distinguish from code-initiated changes from user-initiated ones. The complete code looks somewhat like this:

var auto_center = true;
var ignore_change_events = false;

function gets_called_when_I_have_updated_coords() {
    if (auto_center) {
        ignore_change_events = true;
        map.getView.setCenter(coords);
        ignore_change_events = false;
    }
}

map.getView().on('change:center', function() {
    if (ignore_change_events) {
        return;
    }
    auto_center = false;
});

请注意,如果使用任何动画,则此方法会中断(并且动画结束时没有回调或事件).

Note that this approach breaks if any animation is used (and there is no callback or event for when an animation finishes).

根据您的项目,您可能想要尝试此解决方案或Jonatas Walker 的解决方案.

Depending on your project, you may want to try either this solution or Jonatas Walker's solution.

这篇关于每当用户与地图交互时如何执行一些代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆