Reputation: 5667
I'm trying to restrict autocomplete to a specific country, i.e. USA. How can I do this? I've tried the following below, by passing the variable options as a parameter into the initialization function:
<script>
var autocomplete = {};
var autocompletesWraps = ['test', 'test2'];
var test_form = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' };
var test2_form = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' };
function initialize() {
var options = {
types: ['(cities)'],
componentRestrictions: {country: "us"}
};
$.each(autocompletesWraps, function(index, name) {
if($('#'+name).length == 0) {
return;
}
autocomplete[name] = new google.maps.places.Autocomplete($('#'+name+' .autocomplete')[0], { types: ['geocode'] }, options);
google.maps.event.addListener(autocomplete[name], 'place_changed', function() {
var place = autocomplete[name].getPlace();
var form = eval(name+'_form');
for (var component in form) {
$('#'+name+' .'+component).val('');
$('#'+name+' .'+component).attr('disabled', false);
}
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (typeof form[addressType] !== 'undefined') {
var val = place.address_components[i][form[addressType]];
$('#'+name+' .'+addressType).val(val);
}
}
});
});
}
</script>
Upvotes: 3
Views: 12872
Reputation: 77
If you want to integrate the Google Address API with only United Kingdom address. Please find the below address :
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places" async defer></script>
<script type="text/javascript>
var autocomplete;
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('txtpostcode')),
{ types: ['geocode'] });
autocomplete.setComponentRestrictions(
{'country': ['uk']});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
});
}
</script>
Upvotes: 2
Reputation: 2518
You're not passing the options
correctly. Autocomplete
takes two arguments, and you're passing three.
Specifically, in this line:
autocomplete[name] = new google.maps.places.Autocomplete(
$('#'+name+' .autocomplete')[0], { types: ['geocode'] }, options);
your options
parameter is unused, because you've passed { types: ['geocode'] }
as the options.
So remove the extra argument:
var options = {
types: ['geocode'], // or '(cities)' if that's what you want?
componentRestrictions: {country: "us"}
};
autocomplete[name] = new google.maps.places.Autocomplete(
$('#'+name+' .autocomplete')[0], options);
Upvotes: 5