Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google GeoCode Autocomplete limit State

I am trying to add an Google Geocode Autocomplete field to my form.

I have been able to get it to restrict the results returned to the country (AU) but it would be even better if I could limit the results to the state as well. (New South Wales/NSW)

This is my current initialize() function:

function initialize() {
var options = {
types: ['geocode'],
    componentRestrictions: {country:"AU"}
};
  autocomplete = new google.maps.places.Autocomplete(
  (document.getElementById('autocomplete')),options);
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
  fillInAddress();
  });
}

I have read the documentation and found that you can use the types parameter to restrict the results, but I have been unable to work out what the exact code should be.

Simply changing it to:

types: ['administrative_area1':'NSW'], // OR 'New South Wales'

and various combinations similar to the above (= instead of : etc) have not worked..

Could someone point me in the right direction towards what the actual syntax is for what I am trying to achieve?

Thanks.

like image 496
Jake Avatar asked Feb 19 '14 04:02

Jake


1 Answers

Keep a list of state lat/long boundaries in your app and restrict autocomplete with them.

    var stateBounds={
        ca: ["32.812736", "-119.216815", "34.608128", "-117.039301"]
        // lat/long boundaries list for states/provinces.
    };

    function getStateBounds(state) {
        return new google.maps.LatLngBounds(
          new google.maps.LatLng(stateBounds[state][0], 
                                 stateBounds[state][1]), 
          new google.maps.LatLng(stateBounds[state][2], 
                                 stateBounds[state][3])
        ); 
    }

    new google.maps.places.Autocomplete(document.getElementById('search'), {
        types: ['address'],
        componentRestrictions: {country: 'us'},
        bounds: getStateBounds('ca') // get LatLngBounds for ca.
    });
like image 50
Varol Avatar answered Sep 28 '22 04:09

Varol