Use of the moveend event.
In this example, a listener is registered for the map's moveend
event. Whenever this listener is called, it updates the inputs below with the map extent in decimal degrees.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Moveend Event</title>
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<label>top</label><input type="text" id="top">
<label>right</label><input type="text" id="right"><br>
<label>bottom</label><input type="text" id="bottom">
<label>left</label><input type="text" id="left">
<script src="index.js"></script>
</body>
</html>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import {getBottomLeft, getTopRight} from 'ol/extent';
import TileLayer from 'ol/layer/Tile';
import {toLonLat} from 'ol/proj';
import OSM from 'ol/source/OSM';
var 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) {
var worlds = Math.floor((value + 180) / 360);
return value - (worlds * 360);
}
function onMoveEnd(evt) {
var map = evt.map;
var extent = map.getView().calculateExtent(map.getSize());
var bottomLeft = toLonLat(getBottomLeft(extent));
var 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);
{
"name": "moveend",
"dependencies": {
"ol": "6.1.1"
},
"devDependencies": {
"parcel": "1.11.0"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --experimental-scope-hoisting --public-url . index.html"
}
}