Lamia
Lamia

Reputation: 11

Routing between two points in Mapbox

I am using MapBox to create a route between two points. I have LatLng of two points already and have successfully added Markers at source and destination points. The problem is how to map or connect between these two points using curved lines (route) when the user clicks on the source point? e.g flights routes map

Upvotes: 0

Views: 1653

Answers (1)

Moritz
Moritz

Reputation: 1790

If you want to draw arcs lines that connect 2 points on the earth surface, you do not have to worry about the curvature, as the shortest line between 2 points on a sphere is curved.

The below should do the trick and draw a curved line between San Francisco and Washington DC on your Mapbox GL JS map:

// San Francisco
var origin = [-122.414, 37.776];
 
// Washington DC
var destination = [-77.032, 38.913];
 
// A simple line from origin to destination.
var route = {
    'type': 'FeatureCollection',
    'features': [
        {
            'type': 'Feature',
            'geometry': {
                'type': 'LineString',
                'coordinates': [origin, destination]
            }
        }
    ]
};

map.on('load', function () {
    // Add a source and layer displaying a point which will be animated in a circle.
    map.addSource('route', {
        'type': 'geojson',
        'data': route
    });

    map.addLayer({
        'id': 'route',
        'source': 'route',
        'type': 'line',
        'paint': {
            'line-width': 2,
            'line-color': '#007cbf'
        }
    });

});

Upvotes: 1

Related Questions