mapbox-gl-geocoder icon indicating copy to clipboard operation
mapbox-gl-geocoder copied to clipboard

Change countries option after init

Open dpDesignz opened this issue 3 years ago • 1 comments

I'm using the MapboxGeocoder with the countries option set to a default country, but I would like to update this option if they change the country they are wanting 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
  }
});

dpDesignz avatar Nov 19 '22 00:11 dpDesignz

hey @dpDesignz

I think you can try to set countries geocoder option after init via setter method setCounties and then just call setInput with current search input value to trigger query to API, so the final code would be something similar to

// Country selection changed
$('#country_id').on('change', function(evt, params) {
  // Check it's not empty
  if (params) {
    geocoder.setCountries(newCountries);
    geocoder.setInput(searchInput);
  }
});

VladislavMedved avatar Jan 03 '23 13:01 VladislavMedved