[GIS] how to pass coordinates to a variable from a geojson source in mapbox gl

geojsonjavascriptmapbox-gl-js

I tried with this code but it wont load the coordinates.the source is fine because it appears in the map when i added it..

map.addSource("villa-route-source",{
type: "geojson",
data: "https://api.myjson.com/bins/h71ul"
})
var route = map.addLayer( {
"id": "villa-route",
"type": "LineString",
"source": "villa-route-source",
"paint": {
       "line-color": "#888",
       "line-width": 8
     }
});
var coordinates = route.features[0].geometry.coordinates;

my purpose is to use the geojson into the turf.along and take its coordinates at specific interval and make a line animation..
I can easily put the geojson code easily and it would work but i want it to be a external source.

Best Answer

You can use map.querySourceFeatures, to query the source features within the current viewport.

As noted in the documentation:

Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple times in query results.

If you need access to the original uncut geometry or the geometry outside the viewport I would suggest download the GeoJSON outside of your Mapbox code so you have access it as a global object. Then like the second example you can just pass the GeoJSON object which you already downloaded when you create the source https://www.mapbox.com/mapbox-gl-js/api/#geojsonsource.