Synchronizing map state with the URL.
The Link
interaction allows you to synchronize the map state with the URL. The view center, zoom level, and rotation will be reflected in the URL as you navigate around the map. Layer visibility is also reflected in the URL. Reloading the page restores the map view state.
The interaction can also be used to track other parts of your application state. For example, toggling the checkbox below updates the URL. Navigating back through history will also update the state of the checkbox.
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import Link from 'ol/interaction/Link.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.js';
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const link = new Link();
const exampleCheckbox = document.getElementById('example-checkbox');
exampleCheckbox.addEventListener('change', function () {
if (exampleCheckbox.checked) {
link.update('example', 'checked');
} else {
// updating to null will remove the param from the URL
link.update('example', null);
}
});
const initialValue = link.track('example', (newValue) => {
exampleCheckbox.checked = newValue === 'checked';
});
exampleCheckbox.checked = initialValue === 'checked';
map.addInteraction(link);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Map Link</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>
<input type="checkbox" id="example-checkbox">
See the <code>example</code> search parameter update when toggling this checkbox.
</label>
<script type="module" src="main.js"></script>
</body>
</html>
{
"name": "link",
"dependencies": {
"ol": "10.5.0"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}