原文链接及内容

运行界面

在此示例中,当指针悬停在要素上时,在Map对象针对pointermove事件注册了一个侦听器,以在提示框中显示要素信息。

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import GeoJSON from 'ol/format/GeoJSON.js';
import Map from 'ol/Map.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import View from 'ol/View.js';

const vector = new VectorLayer({
source: new VectorSource({
url: 'https://openlayers.org/data/vector/ecoregions.json',
format: new GeoJSON(),
}),
background: 'white',
style: {
'fill-color': ['string', ['get', 'COLOR'], '#eeeeee'],
},
});

const map = new Map({
layers: [vector],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});

const info = document.getElementById('info');

let currentFeature;
const displayFeatureInfo = function (pixel, target) {
const feature = target.closest('.ol-control')
? undefined
: map.forEachFeatureAtPixel(pixel, function (feature) {
return feature;
});
if (feature) {
info.style.left = pixel[0] + 'px';
info.style.top = pixel[1] + 'px';
if (feature !== currentFeature) {
info.style.visibility = 'visible';
info.innerText = feature.get('ECO_NAME');
}
} else {
info.style.visibility = 'hidden';
}
currentFeature = feature;
};

map.on('pointermove', function (evt) {
if (evt.dragging) {
info.style.visibility = 'hidden';
currentFeature = undefined;
return;
}
const pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel, evt.originalEvent.target);
});

map.on('click', function (evt) {
displayFeatureInfo(evt.pixel, evt.originalEvent.target);
});

map.getTargetElement().addEventListener('pointerleave', function () {
currentFeature = undefined;
info.style.visibility = 'hidden';
});

界面布局文件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
39
40
41
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tooltip on Hover</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
#map {
position: relative;
}

#info {
position: absolute;
display: inline-block;
height: auto;
width: auto;
z-index: 100;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 4px;
padding: 5px;
left: 50%;
transform: translateX(3%);
visibility: hidden;
pointer-events: none;
}
</style>
</head>
<body>
<div id="map" class="map">
<div id="info"></div>
</div>

<script type="module" src="main.js"></script>
</body>
</html>

我们在鼠标悬浮时,要是捕获到要素,更改鼠标样式方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
this.mapMoveKey = map.on("pointermove", (evt) => {
if (evt.dragging) return;
const pixel = map.getEventPixel(evt.originalEvent);
const feature = map.forEachFeatureAtPixel(pixel, (feature) => {
return feature;
});
if (feature) {
this.$refs.wrap.style.cursor = "pointer";
} else {
this.$refs.wrap.style.cursor = "auto";
}
});