1、前言
在OpenLayers
的开发中,事件的身影随处可见。例如,用户点击地图后弹出了一个对话框,这就是事件的典型应用。下面就来介绍一下如何在OpenLayers
中注册事件和取消注册事件。
2、注册事件
事件的注册方式很简单,遵循如下模板即可。其中,事件名称可以是click
、dblclick
、pointermove
等等,后面的function(event)
负责编写该事件的处理逻辑。
map.on('事件名称', function (event) {});
下面就来实现一个小功能:点击地图后显示鼠标点击位置的经纬度,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>OpenLayers</title>
<style>
html, body, #map {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
<link href="ol/ol.css" rel="stylesheet" />
<script src="ol/ol.js"></script>
</head>
<body>
<div id="map"></div>
<script>
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
projection: 'EPSG:3857',
center: ol.proj.transform([120, 30], 'EPSG:4326', 'EPSG:3857'),
zoom: 10
})
});
// click事件
map.on('click', function (event) {
let coordinate = ol.proj.transform(event.coordinate, 'EPSG:3857', 'EPSG:4326');
let message = coordinate[0].toFixed(2) + ',' + coordinate[1].toFixed(2);
window.alert(message);
});
</script>
</body>
</html>
运行结果如下所示:
3、取消注册事件
取消注册事件的模板如下所示:
map.un('事件名称', handler);
现在我们把上面的例子改一改:用户只在第一次点击地图时弹出对话框,其他时候不显示对话框。代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>OpenLayers</title>
<style>
html, body, #map {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
<link href="ol/ol.css" rel="stylesheet" />
<script src="ol/ol.js"></script>
</head>
<body>
<div id="map"></div>
<script>
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
projection: 'EPSG:3857',
center: ol.proj.transform([120, 30], 'EPSG:4326', 'EPSG:3857'),
zoom: 10
})
});
// 定义一个事件处理函数
var handler = function (event) {
let coordinate = ol.proj.transform(event.coordinate, 'EPSG:3857', 'EPSG:4326');
let message = coordinate[0].toFixed(2) + ',' + coordinate[1].toFixed(2);
window.alert(message);
map.un('click', handler);
}
// click事件
map.on('click', handler);
</script>
</body>
</html>
大家可以自行测试一下效果。
4、结语
在OpenLayers
中还存在很多其他的事件,我这里也只是小试牛刀,只介绍了最常用的click
事件,其他常用的地图事件我会在下一篇博客中进行介绍。