Reputation: 82
I need not get the city names in accordance with selected country. I have dropdown list of countries from database.
By default users can select cities from the field i.e no restriction. But when they select country the result in cities should only get the cities of that country.
google.maps.event.addDomListener(window, 'load', intiGoogleLocation);
function intiGoogleLocation() {
var options = {
types: ['(cities)']
};
if (typeof country !== 'undefined') {
options.componentRestrictions = {country: country};
}
function fillInAddress() {
//some custom logic
}
var input = document.getElementById('cities');
var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.addListener('place_changed', fillInAddress);
}
So question is how do i reset the option so that i can set the country to options.componentRestrictions
Upvotes: 1
Views: 1454
Reputation: 117314
Observe the change
-event of the dropdown and set the componentRestrictions
of the autocomplete to the desired value(based on the selected dropdown-item)
function intiGoogleLocation() {
function fillInAddress() {
//some custom logic
console.log('place-name:'+this.getPlace().name);
}
var list = document.getElementById('countries'),
input = document.getElementById('cities'),
autocomplete = new google.maps.places.Autocomplete(input, {
types: ['(cities)']
});
google.maps.event.addListener(autocomplete,'place_changed', fillInAddress);
google.maps.event.addDomListener(list,'change', function(e){
var componentRestrictions={};
if(this.value!==''){
componentRestrictions.country=this.value
}
autocomplete.setComponentRestrictions(componentRestrictions);
input.value='';
if(e){
autocomplete.set('place',{name:''});
}
});
google.maps.event.trigger(list,'change',null);
}
<select id="countries">
<option value="">any country</option>
<option value="de">Germany</option>
<option value="it">Italy</option>
<option value="fr">France</option>
<option value="gb">Great Britain</option>
</select>
<input id="cities"/>
<script src="https://maps.googleapis.com/maps/api/js?v=3&callback=intiGoogleLocation&libraries=places" async defer></script>
Upvotes: 2