2

I'd like to draw a line in mapbox-gl. Something like so:

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

line.remove();

Everywhere I search, this comes up as really complicated involving GeoJson and Layers.

1 Answer 1

3

It turns out it is very complicated and does necessitate GeoJson and Layers. This may make it seem like you're doing something wrong. Anyways, you can fairly easily make your own Polyline class.

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.