Home > Enterprise >  Mapbox zoom level per country
Mapbox zoom level per country

Time:03-21

Hi i'm trying to find a way to show a country fully by country code in Mapbox.

I'm using country-iso-to-coordinates to get the coordinates by country-iso code

For example userCountry = "FR" (France) results in 2.213749, 46.227638 as center points. This works, but i'd also like to have the zoom level fitting the country's boundaries. France for example looks perfect at zoom level 4.3, while big countries like USA or China need zoom level of ~2.2.

data() {
    return {
        accessToken: 'xxxxx',
        mapStyle: 'mapbox://styles/psteger/cl0y1upof001f16sxix3n00oe',
        center: [10, 51],
        zoom: 4.3,
        minZoom: 2.2,
        maxZoom: 14,
        markers: [],
        params: {
            access_token: 'xxxxx',
            country: 'de',
            language: 'en'
        }
    }
},
mounted() {
    const coordinates = IsoToLatLong[this.userCountry];
    this.center = [coordinates.coordinate[1], coordinates.coordinate[0]]
},

How can i find a working zoom level that shows the whole country without manually trying and writing a list for each single country? Is there a package with ratios of each country so i could calculate the zoom levels or can mapbox's API set a zoom level by a country's borders?

Thanks for any help!

CodePudding user response:

I suggest using country-bounding-boxes which would allow you the following method:

import boundingBoxes from 'country-bounding-boxes/bounding-boxes.json';

export default {
  // ...
  methods: {
    zoomToCountry(isoCode) {
      this.map.fitBounds(boundingBoxes[isoCode][1]);
    }
  }
}

Here's a pretty basic working demo.

  • Related