Vector 瓦片 选择
Vector 瓦片 选择示例。 vectortiles 选择
点击一个已渲染的矢量瓦片要素,可在地图上高亮显示它。点击空白处(海洋)可重置选择。 将操作类型改为 "Multi Select" 后,可以一次选择多个要素。选择 "Single Select on hover" 时, 当鼠标指针位于要素上方时,要素会被高亮。
选择图层配置了 renderMode: 'vector',以便在频繁重绘时获得更好的性能, 例如选择 "Single Select on hover" 时。
main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import MVT from 'ol/format/MVT.js';
import VectorTileLayer from 'ol/layer/VectorTile.js';
import VectorTileSource from 'ol/source/VectorTile.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';
// 选择对象的查找表
let selection = {};
const country = new Style({
stroke: new Stroke({
color: 'gray',
width: 1,
}),
fill: new Fill({
color: 'rgba(20,20,20,0.9)',
}),
});
const selectedCountry = new Style({
stroke: new Stroke({
color: 'rgba(200,20,20,0.8)',
width: 2,
}),
fill: new Fill({
color: 'rgba(200,20,20,0.4)',
}),
});
const vtLayer = new VectorTileLayer({
declutter: true,
source: new VectorTileSource({
maxZoom: 15,
format: new MVT({
idProperty: 'iso_a3',
}),
url:
'https://ahocevar.com/geoserver/gwc/service/tms/1.0.0/' +
'ne:ne_10m_admin_0_countries@EPSG%3A900913@pbf/{z}/{x}/{-y}.pbf',
}),
style: country,
});
const map = new Map({
layers: [vtLayer],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
multiWorld: true,
}),
});
// 选择
const selectionLayer = new VectorTileLayer({
map: map,
renderMode: 'vector',
source: vtLayer.getSource(),
style: function (feature) {
if (feature.getId() in selection) {
return selectedCountry;
}
},
});
const selectElement = document.getElementById('type');
map.on(['click', 'pointermove'], function (event) {
if (
(selectElement.value === 'singleselect-hover' &&
event.type !== 'pointermove') ||
(selectElement.value !== 'singleselect-hover' &&
event.type === 'pointermove')
) {
return;
}
vtLayer.getFeatures(event.pixel).then(function (features) {
if (!features.length) {
selection = {};
selectionLayer.changed();
return;
}
const feature = features[0];
if (!feature) {
return;
}
const fid = feature.getId();
if (selectElement.value.startsWith('singleselect')) {
selection = {};
}
// 将选中的要素加入查找表
selection[fid] = feature;
selectionLayer.changed();
});
});index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vector 瓦片选择</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>
<form>
<label for="type">操作类型 </label>
<select id="type">
<option value="singleselect" selected>单选</option>
<option value="multiselect">多选</option>
<option value="singleselect-hover">悬停时单选</option>
</select>
</form>
<script type="module" src="main.js"></script>
</body>
</html>package.json
json
{
"name": "vector-tile-selection",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}