Search code examples
javascriptgoogle-mapsgoogle-maps-api-3autocompletegoogle-maps-autocomplete

Google API Autocomplete, Only one region type


I am currently using the google apis API to autocomplete locations. I can set it to only return the regions type with "autocomplete.setTypes(['regions'])" . Looking at the documentation I can see that regions type will return all results containing the following types;
* locality
* sublocality
* postal_code
* country
* administrative_area1
* administrative_area2

What I want to achieve though, is to only return autocomplete predictions with the region type "sublocality". Is this possible? If not has anybody had a similar issue and have an alternative solution they would recommend? Thank you.

var autocomplete = new google.maps.places.Autocomplete(input);

var types = ['(regions)'];

var options = {
    componentRestrictions: {country: 'uk'}
};

autocomplete.setTypes(types);
autocomplete.setOptions(options);


Solution

  • You could filter your query predictions results to only display (or do whatever you like with it, as we don't know what you are trying to do) a prediction if it has a type of sublocality as each result comes with an array of types.

    Something like that:

    // Build output for each prediction
    for (var i = 0, prediction; prediction = predictions[i]; i++) {
    
      if (prediction['types'].includes('sublocality')) {
    
        // Display it or do what you need to do here
      }
    }
    

    Bare in mind though that query predictions only return a maximum of 5 results, so it might be confusing for the end-user as nothing at all might show until you enter quite a few letters...