openlayer实现矢量图层点击高亮效果
# 概述
本文主要介绍如何在 Openlayers 矢量图层上实现点击高亮效果。
# 效果演示
# 具体实现
数据准备
矢量数据可点击下载
加载矢量图层
矢量数据是通过调用Openlayers
的new GeoJSON()
实例去加载读取。
let style = new Style({
fill: new Fill({
color: "rgba(255, 255, 255, 0.6)",
}),
stroke: new Stroke({
color: "#319FD3",
width: 1,
}),
text: new Text({
font: "12px Calibri,sans-serif",
fill: new Fill({
color: "#000",
}),
stroke: new Stroke({
color: "#fff",
width: 3,
}),
}),
});
let vectorLayer = new LayerVector({
source: new SourceVector({
features: new GeoJSON({
featureProjection: "EPSG:3857",
}).readFeatures(lands),
format: new GeoJSON(),
wrapX: true,
}),
style: (feature) => {
style.getText().setText(feature.get("name"));
return style;
},
});
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
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
绑定事件
监听地图click
和pointermove
事件,获取点击位置的像素点信息,就是点在整个浏览器屏幕的位置
map.on("pointermove", (evt) => {
if (evt.dragging) {
return;
}
let pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel);
});
map.on("click", (evt) => {
displayFeatureInfo(evt.pixel);
});
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
定义displayFeatureInfo
方法
该方法主要就是通过 Openlayers 的map.forEachFeatureAtPixel
方法和点击位置获取点击的feature
,再对feature
进行添加到高亮图层中显示。
具体实现如下:
displayFeatureInfo(pixel) {
// 创建高亮图层
if (!featureOverlay) {
featureOverlay = new LayerVector({
source: new SourceVector(),
map: map,
style: (feature) => {
highlightStyle
.getText()
.setText(feature.get("name"));
return highlightStyle;
},
});
}
// 获取点击的要素
let feature = map.forEachFeatureAtPixel(
pixel,
(feature) => feature
);
// 设置高亮要素
if (feature !== highlight) {
if (highlight) {
featureOverlay
.getSource()
.removeFeature(highlight);
}
if (feature) {
featureOverlay.getSource().addFeature(feature);
}
highlight = feature;
}
}
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
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
编辑 (opens new window)
上次更新: 2024/10/18, 08:17:41