地图链接
地图链接示例。 链接 permalink url query search params
Link 交互允许你将地图状态与 URL 同步。在地图上浏览时,视图中心、缩放级别和旋转角度都会反映到 URL 中,图层的可见性也会反映在 URL 中。重新加载页面即可恢复地图的视图状态。 该交互还可用于跟踪应用状态的其他部分。例如,切换下方的复选框会更新 URL,而在历史记录中后退也会更新复选框的状态。
main.js
js
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 {
// 更新为 null 会将该参数从 URL 中移除
link.update('example', null);
}
});
const initialValue = link.track('example', (newValue) => {
exampleCheckbox.checked = newValue === 'checked';
});
exampleCheckbox.checked = initialValue === 'checked';
map.addInteraction(link);index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>地图链接</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">
切换此复选框时,查看 <code>example</code> 搜索参数的更新。
</label>
<script type="module" src="main.js"></script>
</body>
</html>package.json
json
{
"name": "link",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}