如何在Mapbox GL中创建线条

  • 本文关键字:创建 GL Mapbox mapbox-gl
  • 更新时间 :
  • 英文 :


我想在地图框gl中画一条线。类似的东西:

const line = new Polyline({
points: [
{ lat: 0, lng: 0},
{ lat: 1, lng: 1},
]
});
line.addTo(map);
line.remove();

无论我在哪里搜索,都会发现涉及GeoJson和Layers的情况非常复杂。

事实证明,它非常复杂,确实需要GeoJson和Layers。这可能会让人觉得你做错了什么。无论如何,您可以很容易地创建自己的Polyline类。

export interface IPolylineProps {
id: string;
points: Array<[number, number] | { lat: number, lng: number }>
layout?: mapboxgl.LineLayout;
paint?: mapboxgl.LinePaint;
}
export class Polyline {
constructor(private props: IPolylineProps) {}
protected map: mapboxgl.Map;
public addTo(map: mapboxgl.Map) {
if (this.map) {
this.remove();
}
this.map = map;
map.addLayer({
'id': this.props.id,
'type': 'line',
'source': {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'LineString',
'coordinates': this.props.points.map((point) => {
return Array.isArray(point) ? point : [point.lng, point.lat]
})
}
}
},
'layout': this.props.layout || {
'line-join': 'round',
'line-cap': 'round'
},
'paint': this.props.paint || {
'line-color': '#888',
'line-width': 3
}
})
}
public remove() {
if (!this.map) { return; }
this.map.removeLayer(this.props.id);
this.map.removeSource(this.props.id);
this.map = undefined;
}
}

最新更新