Joey
Joey

Reputation: 33

Drawing a line in mapbox-gl using coordinates from an array?

I am trying to draw a line on mapbox using coordinates from an api request. The api call retrieves an array of map points latitude and longitude values. I had tried using the example for creating a geojson line at this website: https://www.mapbox.com/mapbox-gl-js/example/geojson-line/ however this example and every other example I found only showed adding layers to the map containing hardcoded coordinates rather than coordinates that will be retrieved from another source later.

What I originally thought would work is simply creating an array of lat/longs in the appropriate format then putting that array equal to the coordinates when adding a layer, like so:

    var lineArray = [];
    for(var i = 0; i < response.mapPoints.length; i++)
    {
        lineArray[i] = " [" + response.mapPoints[i].lng + ", " + response.mapPoints[i].lat + "]";
    }
    map.addLayer({
        "id": "route",
        "type": "line",
        "source": {
            "type": "geojson",
            "data": {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "type": "LineString",
                    "coordinates": [
                        lineArray
                    ]
                }
            }
        },
        "layout": {
            "line-join": "round",
            "line-cap": "round"
        },
        "paint": {
            "line-color": "#888",
            "line-width": 8
        }
    }); 

The lineArray looked correct after printing it out. I was able to create a small line using a for loop and changing the add layer code to look like the following:

"coordinates": [
[ response.mapPoints[i].lng, response.mapPoints[i].lat ],
[ response.mapPoints[i+1].lng, response.mapPoints[i+1].lat ]
]

however this took way too long since I am using thousands of coordinates at a time and am having to loop through every single one in order to draw the line.

Am I on the right track at all? Any help or direction to a similar example would be greatly appreciated!

Upvotes: 3

Views: 6697

Answers (1)

pathmapper
pathmapper

Reputation: 1927

You could use Turf.js for creating a LineString feature from an array of positions (http://turfjs.org/docs/#lineString) and use this LineString as a source for a line layer:

Example (based on https://www.mapbox.com/mapbox-gl-js/example/geojson-line/):

http://jsbin.com/beziyolisu/1/edit?html,output

var positions =[
                [lon_1, lat_1],
                ...
                [lon_n, lat_n]
               ]; 

var linestring = turf.lineString(positions);

map.on('load', function () {

    map.addLayer({
        "id": "route",
        "type": "line",
        "source": {
            "type": "geojson",
            "data": linestring
        },
        "layout": {...},
        "paint":{...},
    });

});

Upvotes: 5

Related Questions