用mapbox绘制多条路线,如何实现点击某条线,实现这条线的高亮呢?
export class MapComponent {
public pathLine: string = 'path-line';
public sourceNames: any = new Set();
initPathLine() { //初始化
if (!this.map.getSource(this.pathLine)) {
this.map.addSource(this.pathLine, {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [],
},
});
this.sourceNames.add(this.pathLine);//收集信息
}
if (!this.map.getLayer(this.pathLine + '-layer')) {
this.map.addLayer({
type: 'line',
source: this.pathLine,
id: this.pathLine + '-layer',
paint: {
'line-color': '#01c76f',
'line-width': 6,
},
});
this.sourceNames.add(this.pathLine + '-layer');//收集信息
}
}
createPathLine(data: any) {
this.initPathLine();//初始化信息
if (this.map.getSource(this.pathLine)) {
const arr: any = [];
data.map((item: any, index: number) => {
//创建路线
const feature: any = {
type: 'Feature',
properties: {//属性信息,这里储存的序号index,也可以是别的,在changeLineColor方法用的到
category: index, //category是自定义的键名,可以随便写
},
geometry: {
coordinates: item.lineCoordinates,
type: 'LineString',
},
};
arr.push(feature);
});
//赋值操作
if (this.map.getSource(this.pathLine)) {
this.map.getSource(this.pathLine).setData({
type: 'FeatureCollection',
features: arr,
});
}
//视角飞入
this.map.flyTo({
center: data[0]['lineCoordinates'][0],
zoom: 12,
});
}
}
changeLineColor(index:number){ //高亮
this.map.setPaintProperty(
this.pathLine + '-layer',
'line-opacity',
['match', ['get', 'category'], index, 1, 0.5] //根据category属性进行筛选,符合条件的就是1,否则就是0.5
);
}
clearData() {//清除数据
if (this.sourceNames.size > 0) {
console.log(this.sourceNames);
this.sourceNames.forEach((v: any) => {
//注意顺序,必须先清除layer
console.log(v);
if (this.map.getLayer(v)) {
this.map.removeLayer(v);
}
if (this.map.getSource(v)) {
this.map.removeSource(v);
}
});
this.sourceNames.clear(); //清空容器
}
}
}
网友评论