WMS GetFeatureInfo (瓦片 图层)
WMS GetFeatureInfo (瓦片 图层)示例。 getfeatureinfo getData
本示例展示如何在 WMS 瓦片图层上通过点击触发 WMS GetFeatureInfo 请求。此外还使用 layer.getData(pixel) 在鼠标悬停到地图上非透明像素时改变鼠标指针。
main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import TileWMS from 'ol/source/TileWMS.js';
const wmsSource = new TileWMS({
url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'ne:ne', 'TILED': true},
serverType: 'geoserver',
crossOrigin: 'anonymous',
});
const wmsLayer = new TileLayer({
source: wmsSource,
});
const view = new View({
center: [0, 0],
zoom: 1,
});
const map = new Map({
layers: [wmsLayer],
target: 'map',
view: view,
});
map.on('singleclick', function (evt) {
document.getElementById('info').innerHTML = '';
const viewResolution = view.getResolution();
const url = wmsSource.getFeatureInfoUrl(
evt.coordinate,
viewResolution,
'EPSG:3857',
{'INFO_FORMAT': 'text/html'},
);
if (url) {
fetch(url)
.then((response) => response.text())
.then((html) => {
document.getElementById('info').innerHTML = html;
});
}
});
map.on('pointermove', function (evt) {
if (evt.dragging) {
return;
}
const data = wmsLayer.getData(evt.pixel);
const hit = data && data[3] > 0; // 透明像素的 data[3] 为零
map.getTargetElement().style.cursor = hit ? 'pointer' : '';
});index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WMS GetFeatureInfo(瓦片图层)</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>package.json
json
{
"name": "getfeatureinfo-tile",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}