在带有保护状态的生态区矢量图层上命中检测的示例。
生态区数据从 GeoJSON 文件加载。通过图层的 getFeatures() 方法在悬停和点击时检索要素信息。对于矢量图层,此函数仅解析为最顶层要素的数组。它使用高效的命中检测算法,但以精度为代价。当性能不是问题时,如需像素级精确的命中检测,请使用地图的 getFeaturesAtPixel() 或 forEachFeatureAtPixel() 方法。
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
const vectorLayer = new VectorLayer({
background: '#1a2b39',
source: new VectorSource({
url: 'https://openlayers.org/data/vector/ecoregions.json',
format: new GeoJSON(),
}),
style: {
'fill-color': ['string', ['get', 'COLOR_NNH'], '#eee'],
},
});
const map = new Map({
layers: [vectorLayer],
target: 'map',
view: new View({
center: [0, 0],
zoom: 1,
}),
});
const featureOverlay = new VectorLayer({
source: new VectorSource(),
map: map,
style: {
'stroke-color': 'rgba(255, 255, 255, 0.7)',
'stroke-width': 2,
},
});
let highlight;
const displayFeatureInfo = function (pixel) {
vectorLayer.getFeatures(pixel).then(function (features) {
const feature = features.length ? features[0] : undefined;
const info = document.getElementById('info');
if (features.length) {
info.innerHTML = feature.get('ECO_NAME') + ': ' + feature.get('NNH_NAME');
} else {
info.innerHTML = ' ';
}
if (feature !== highlight) {
if (highlight) {
featureOverlay.getSource().removeFeature(highlight);
}
if (feature) {
featureOverlay.getSource().addFeature(feature);
}
highlight = feature;
}
});
};
map.on('pointermove', function (evt) {
if (evt.dragging) {
return;
}
displayFeatureInfo(evt.pixel);
});
map.on('click', function (evt) {
displayFeatureInfo(evt.pixel);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vector Layer Hit Detection</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>
<div id="info"> </div>
<script type="module" src="main.js"></script>
</body>
</html>
{
"name": "hitdetect-vector",
"dependencies": {
"ol": "10.9.0"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}