I'm using Mapbox GL JS to load in GeoJSON from an external URL on some pages. I would like to automatically fit the map to the boundaries of the polygon I'm loading.
I understand that turf.js's bbox method can help with this, but I'm not sure how to get the GeoJSON into the turf.bbox
call.
This is my code right now:
map.addSource('mylayer', {
type: 'geojson',
data: '/boundaries.geojson'
});
map.addLayer({
"id": "mylayer",
"type": "fill",
"source": "mylayer",
'paint': {
'fill-color': '#088',
'fill-opacity': 0.6
}
});
var bbox = turf.bbox('mylayer');
map.fitBounds(bbox, {padding: 20});
But it fails with turf.min.js:1 Uncaught Error: Unknown Geometry Type
. The docs say that bbox
wants "any GeoJSON object".
How do I do this correctly? I'd obviously rather not load the external file twice.