一、功能场景:
二、实现代码:
具体思路:
- 先添加一个fill图层填充多边形区域,line图层显示多边形边框。
- 监听鼠标mousemove和mouseleave事件。
- 鼠标移入的时候创建popup,修改fill图层的透明度和line图层的宽度,移出时还原。
提示:
data为包含图层信息和坐标的对象数据,其中geom为经纬度数组,结构为polygon或MultiPolygon。
代码如下:
data() {
return {
data: [],
popup: null,
};
},
methods: {
renderLayer(){
this.data.forEach((element, index) => {
this.map.addLayer({
id: `${element.id}Fill`,
type: 'fill',
source: {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: element.geom
}
]
}
},
paint: {
'fill-color': 'orange',
'fill-opacity': 0.2
}
});
this.map.addLayer({
id: `${element.id}Line`,
type: 'line',
source: {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: element.geom
}
]
}
},
paint: {
'line-color': '#003',
'line-width': 2,
'line-opacity': 0.5
}
});
this.map.on('mousemove', `${element.id}Fill`, e => {
this.popup = this.createPopup(e, element);
this.popup.addTo(this.map);
this.map.setPaintProperty(`${element.id}Fill`, 'fill-opacity', 0.5);
this.map.setPaintProperty(`${element.id}Line`, 'line-width', 4);
});
this.map.on('mouseleave', `${element.id}Fill`, () => {
this.map.setPaintProperty(`${element.id}Fill`, 'fill-opacity', 0.2);
this.map.setPaintProperty(`${element.id}Line`, 'line-width', 2);
this.popup.remove();
});
});
},
// 创建popup
createPopup(e, feature) {
if (this.popup) {
this.popup.remove();
}
// 取区域的颜色
const bgc = this.map.getPaintProperty(`${feature.id}bigFill`, 'fill-color');
let html = `<div class="title" style="background: ${bgc}" title="${feature.name}">${
feature.name
}</div>
`;
let popup = new mapboxgl.Popup({
offset: 0,
closeButton: false,
className: 'popup'
})
.setLngLat([e.lngLat.lng, e.lngLat.lat])
.setHTML(html);
return popup;
},
}