原文链接及内容

运行界面

将鼠标指针移动到渲染的要素上以显示要素属性信息。

main.js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import MVT from 'ol/format/MVT.js';
import Map from 'ol/Map.js';
import VectorTileLayer from 'ol/layer/VectorTile.js';
import VectorTileSource from 'ol/source/VectorTile.js';
import View from 'ol/View.js';

const map = new Map({
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
layers: [
new VectorTileLayer({
source: new VectorTileSource({
format: new MVT(),
url: 'https://basemaps.arcgis.com/arcgis/rest/services/World_Basemap_v2/VectorTileServer/tile/{z}/{y}/{x}.pbf',
}),
}),
],
});

map.on('pointermove', showInfo);

const info = document.getElementById('info');
function showInfo(event) {
const features = map.getFeaturesAtPixel(event.pixel);
if (features.length == 0) {
info.innerText = '';
info.style.opacity = 0;
return;
}
const properties = features[0].getProperties();
info.innerText = JSON.stringify(properties, null, 2);
info.style.opacity = 1;
}

界面布局文件index.html代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vector Tile Info</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
#map {
position: relative;
}

#info {
z-index: 1;
opacity: 0;
position: absolute;
bottom: 0;
left: 0;
margin: 0;
background: rgba(0,60,136,0.7);
color: white;
border: 0;
transition: opacity 100ms ease-in;
}
</style>
</head>
<body>
<div id="map" class="map">
<pre id="info"/>
</div>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://cdn.jsdelivr.net/npm/elm-pep@1.0.6/dist/elm-pep.js"></script>
<script type="module" src="main.js"></script>
</body>
</html>