原文链接及内容

运行界面

在本例中,为地图的moveend事件注册了一个侦听器,每当调用此侦听器时,地图的范围都会更新,如上图,地图下方的输入框会随着地图的范围(十进制度)的变化而更新。

main.js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import Map from 'ol/Map.js';
import OSM from 'ol/source/OSM.js';
import TileLayer from 'ol/layer/Tile.js';
import View from 'ol/View.js';
import {getBottomLeft, getTopRight} from 'ol/extent.js';
import {toLonLat} from 'ol/proj.js';

const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});

function display(id, value) {
document.getElementById(id).value = value.toFixed(2);
}

function wrapLon(value) {
const worlds = Math.floor((value + 180) / 360);
return value - worlds * 360;
}

function onMoveEnd(evt) {
const map = evt.map;
const extent = map.getView().calculateExtent(map.getSize());
const bottomLeft = toLonLat(getBottomLeft(extent));
const topRight = toLonLat(getTopRight(extent));
display('left', wrapLon(bottomLeft[0]));
display('bottom', bottomLeft[1]);
display('right', wrapLon(topRight[0]));
display('top', topRight[1]);
}

map.on('moveend', onMoveEnd);

界面布局文件index.html代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Moveend Event</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<label>left: <input readonly="readonly" type="text" id="left"></label>
<label>right: <input readonly="readonly" type="text" id="right"></label>
<label>bottom: <input readonly="readonly" type="text" id="bottom"></label>
<label>top: <input readonly="readonly" type="text" id="top"></label>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://cdn.jsdelivr.net/npm/elm-pep@1.0.6/dist/elm-pep.js"></script>
<script type="module" src="main.js"></script>
</body>
</html>