cappie013
cappie013

Reputation: 2444

How can I prioritize country in Google map autocomplete?

I would like my autocomplete to show a specified country first, than the other countries.

Right now I have this:

const autocompleteService = new window.google.maps.places.AutocompleteService()
const location = window.google.maps.LatLng(48.856614, 2.3522219)
const query = {
  location: location,
  radius: 1000,
  types: ["(cities)"]
}
autocompleteService.getPlacePredictions(query, cb)

But when I'm typing lond, I get London first instead of french cities (such as Londinières)

EDIT:

I also tried with the bounds option, and I'm getting the same results

const bounds = new window.google.maps.LatLngBounds(
  new window.google.maps.LatLng(49.79295, 1.20374),
  new window.google.maps.LatLng(49.921316, 1.498147)
)
const autocompleteService = new window.google.maps.places.AutocompleteService()
const location = window.google.maps.LatLng(48.856614, 2.3522219)
const query = {
  bounds: bounds,
  types: ["(cities)"]
}

Upvotes: 1

Views: 2054

Answers (2)

forrert
forrert

Reputation: 4239

The AutocompletionRequest has a property called componentRestrictions which can be used to provide a list of countries to restrict the search to:

const autocompleteService = new window.google.maps.places.AutocompleteService()
const location = window.google.maps.LatLng(48.856614, 2.3522219)
const query = {
  location: location,
  radius: 1000,
  types: ["(cities)"],
  componentRestrictions: { country: 'fr' }
}
autocompleteService.getPlacePredictions(query, cb)

This may be too restrictive for your purposes, but you may be able to combine the results of this query with your original query to also get suggestions outside of your preferred country.

Upvotes: 2

liakoyras
liakoyras

Reputation: 1185

You can try this code (provided you can find your coordinates first.

var southWest = new google.maps.LatLng(42.97250, -3.82324);
var northEast = new google.maps.LatLng(51.64529, 5.49316);
var bounds = new google.maps.LatLngBounds(southWest,northEast);
var autocomplete = new google.maps.places.Autocomplete(input, {bounds: bounds});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
  //...
});

Upvotes: 0

Related Questions