Reputation: 455
I have a list of countries, and I'm trying to center the map and adjust the zoom level to show the whole country in the map.
Using geocoding APIs https://api.mapbox.com/geocoding/v5/{dataset}/{query}.json?country={cc}&access_token=<your access token>
, I'm able to get some coordinates that are not quite in the center of the country, but at least I get relevant coordinates, however, the returned object doesn't contain any information on the zoom level.
<select id="country" name="country">
<option value="at">Austria</option>
<option value="cy">Cyprus</option>
<option value="de">Germany</option>
<option value="pt">Portugal</option>
<option value="es">Spain</option>
</select>
<div class="map" id="map"></div>
<script>
mapboxgl.accessToken = 'the_access_token';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v8', //stylesheet location
center: [-74.50, 40], // random starting position
zoom: 9 // starting zoom level
});
// Find country
$('#country').on('change', function (e) {
countrycode = $(this).val();
country = $(this).find('option:selected').text();
console.log(countrycode, country);
$.ajax({
url: "https://api.mapbox.com/geocoding/v5/mapbox.places/"+country+".json?country="+countrycode+"&access_token="+mapboxgl.accessToken,
success: function(res) {
console.log(res);
map.easeTo({
center: res.features[0].center,
// zoom:
});
}
});
});
</script>
What am I missing? Should I be using different APIs? Or is what I'm looking for not supported?
Upvotes: 1
Views: 2273
Reputation: 4735
What's also returned in the response is a bounding box which you can pass to map.fitBounds
for accurate coordinates + zoom:
var bbox = res.features[0].bbox;
map.fitBounds([
[bbox[0], bbox[1]],
[bbox[2], bbox[3]]
]);
Upvotes: 5