user2673206
user2673206

Reputation: 215

google map api autosuggest: change restriction dynamically from another address

i am using google map api v3 for gmap automcomplete. may i ask how to set the biased country and city from another address dynamically?

this is my existing code:

<script>
    function initialize() {
        var input_location = document.getElementById('id_location');
        var options_location = {
            componentRestrictions: {country: 'fr'}
        };
        var autocomplete_location = new google.maps.places.Autocomplete(input_location);

    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

From above you can see i restrict the search to france.

But how about i want to change the country based on another address?

example: Geneva International Airport, Grand-Saconnex, Switzerland

Thanks a lot


edit:

one more question ( but this question is closely related with what i am asking above, so i do not ask a new q.) what if the addres is different? example: a1: brazil a2: Geneva International Airport, Grand-Saconnex, Switzerland

from the address_components, i should not always extract the second element as the country.

edit2:

problem solved. i wrote a for loop to check if 'country' is in types to get the country code:

geocoder.geocode({address: address}, function (result, status) {
                if (status === 'OK' && result.length > 0) {
                    var i = 0;
                    len = result[0].address_components.length;
                    for (; i < len; i++){
                        if (result[0].address_components[i].types.indexOf('country') >= 0) {
                            c_code = result[0].address_components[i].short_name;
                        }
                    }

                    var options = {
                        componentRestrictions: {country: c_code }
                    };

                    var input_location = document.getElementById('id_location');
                    var autocomplete_location = new google.maps.places.Autocomplete(input_location, options);

                }
            })

Upvotes: 0

Views: 3031

Answers (3)

lubosdz
lubosdz

Reputation: 4500

Since it may be difficult to change multiple options, it might be better to remove previous listener and create new one with changed options.

Clear current listener:

var autocompleteField = document.getElementById("autocomplete");
google.maps.event.clearInstanceListeners(autocompleteField);

Add new listener depending on e.g. checkbox:

var onlySlovakia = document.getElementById("checkboxOnlySlovakia");

// common restriction
var options = {}

if(onlySlovakia.value == "1"){
    // we want more detailed suggestions
    options.ComponentRestrictions = {country : 'sk'};
    options.types: ['geocode', 'establishment']
}else{
    options.types: ['geocode']
}

// create instance
handle = new google.maps.places.Autocomplete(autocompleteField, options);

// add listener with new options
google.maps.event.addListener(handle, 'place_changed', function() {
    var place = handle.getPlace();
    ... process results ...
});

See also API event namespace.

Upvotes: 0

hennes
hennes

Reputation: 9342

Basically you have two options: create a static mapping or use geocoding.

Static Mapping

Just setup an object that statically maps country long names (like Switzerland) to short names (like CH). Afterwards, determine the country long name from your address by means of common string manipulation functions. You can then simply look up the short name in the mapping object.

var countries = {
    'switzerland': 'CH',
    'germany': 'DE',
    ...
}

var address = 'Geneva International Airport, Grand-Saconnex, Switzerland';
var country = address.substring(address.lastIndexOf(',') + 1);
var code = countries[country.trim().toLowerCase()];

Note that this option does only work if you know all of the countries upfront.

Geocoding

Another way to approach your problem is to geocode the address string and then read the country code from the response.

var geocoder = new google.maps.Geocoder();
geocoder.geocode({
    address: 'Geneva International Airport, Grand-Saconnex, Switzerland'
}, function(result, status) {
    if (status === 'OK' && result.length > 0) {
        var code = result[0].address_components[2].short_name;
    }
});

This alternative does not require you to know all the countries upfront. There is, however, a rate limit in the geocoding API which you might run into.

Upvotes: 2

MrUpsidown
MrUpsidown

Reputation: 22497

Use the setComponentRestrictions() method of the Autocomplete class. See the documentation.

var country = 'fr';
var autocomplete_location = new google.maps.places.Autocomplete(input_location);

autocomplete_location.setComponentRestrictions({'country': country});

Upvotes: 10

Related Questions