dpDesignz
dpDesignz

Reputation: 1959

Change countries option after init with Mapbox Geocoder

I'm using the MapboxGeocoder with the countries option set to a default country, but I would like to update this option if the user changes the country they want to search in.

Current code:

// Add the control to the map.
const geocoder = new MapboxGeocoder({
  accessToken: mapboxgl.accessToken,
  mapboxgl: mapboxgl,
  marker: false,
  countries: 'nz'
});

I'm using the chosen plugin from harvest, so I have the on change function working, I need to know if it's possible to change the countries option when they change the country so that results searched for will only return for the current country they have selected

// Country selection changed
$('#country_id').on('change', function(evt, params) {
  // Check it's not empty
  if (params) {
    // code to go in here to change 'countries' option
  }
});

Upvotes: 0

Views: 428

Answers (1)

Andrew Newby
Andrew Newby

Reputation: 5206

Ok, after some digging I found out how you can do this. I know this is an old question, but I'll post it anyway in case someone else ends up here trying to do the same thing! Looking at the API references here:

https://github.com/mapbox/mapbox-gl-geocoder/blob/main/API.md#setcountries

It turns out there is a setCountries option - so just invoke it with:

placesAutocompleteBilling.setCountries(this.value)

with this.value being the country code (ES, IT, FR, GB etc). It seems to do the trick

Upvotes: 0

Related Questions