项目有个需求,就是我们加载一个市级行政区划图层,当我们鼠标经过某个县级的时候,当前县显示高亮, mapbox官网有个例子,找了好久才解决。当时我用错了鼠标事件,鼠标进入图层是有两个事件的,一个是mouseenter,一个是mousemove,当时我用的是mouseente,导致鼠标每次进入县A的时候图层可以高亮,但是由县A进去到县B的时候却没有效果。后面查阅资料才知道,mouseenter只会监听这个元素,而mousemove监听这个元素并包含其子元素,换了事件后彻底解决。
1、鼠标进入
this.map.map.on("mousemove", layerId, (e) => {
if (this.hoveredStateId !== null) {
this.map.map.setFeatureState(
{ source: 'fanghuozhanPolygon7', id: this.hoveredStateId },
{ hover: false }
);
}
if (e.features[0].id) {
this.hoveredStateId = e.features[0].id;
this.map.map.setFeatureState(
{ source: "fanghuozhanPolygon7", id: this.hoveredStateId },
{ hover: true }
);
this.mousemoveFun(e,layerId)
}
});
//鼠标经过某个县展示不同高亮颜色
mousemoveFun(e, layerId) {
if (layerId == "fanghuozhanPolygon") {
let id = e.features[0].properties.Id;
let name = e.features[0].properties.name;
let matchArr = [];
if (name == "汉江护林防火站") {
matchArr = [
"match",
["get", "Id"],
id,
"rgba(180, 235, 241,1)",
"rgba(192,192,192,1)",
];
} else if (name == "西燕护林防火站") {
matchArr = [
"match",
["get", "Id"],
id,
"rgba(15, 116, 183,1)",
"rgba(192,192,192,1)",
];
} else if (name == "铜矿护林防火站") {
matchArr = [
"match",
["get", "Id"],
id,
"rgba(52, 198, 217,1)",
"rgba(192,192,192,1)",
];
} else if (name == "天枰护林防火站") {
matchArr = [
"match",
["get", "Id"],
id,
"rgba(18, 136, 214,1)",
"rgba(192,192,192,1)",
];
}
this.map.map.setPaintProperty(
"fanghuozhanPolygon",
"fill-color",
matchArr
);
}
},
2、鼠标离开
this.map.map.on("mouseleave", layerId, (e) => {
this.map.map.getCanvas().style.cursor = "default";
if (this.hoveredStateId !== null) {
this.map.map.setFeatureState(
{ source: "fanghuozhanPolygon7", id: this.hoveredStateId },
{ hover: false }
);
}
this.hoveredStateId = null;
this.mouseleaveFun(e,layerId)
});
//鼠标离开的时候恢复到默认图层
mouseleaveFun(e, layerId) {
this.map.map.setPaintProperty('fanghuozhanPolygon', "fill-color", 'rgba(192,192,192,1)');
},