I am trying to get Google Maps address_components
and have only managed to get do the following:
$(function() {
$("#spot_address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
for (var i = 0; i < results[0].address_components.length; i++)
{
var addr = results[0].address_components[i];
if (addr.types[0] == 'country')
country: addr.long_name;
}
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
alert(ui.country);
$("#spot_lat").val(ui.item.latitude);
$("#spot_lng").val(ui.item.longitude);
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
});
Over here I am trying to test the alert(ui.country)
when the item is selected from the autocomplete list. However, I am only getting undefined
instead. It's not passed. What have I done wrong?
Thanks.
Check if property ui.country exists FireBug or Chrome Inspect Scripts
And If property country exist in item then just:
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng(),
country: item.country, // Or other location of this property
}
}));
Add to
response($.map(results, function(item) {
return {
country: item.country
Finally got it done with a help of a friend.
Here's the full code:
$(function() {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
for (var i = 0; i < results[0].address_components.length; i++)
{
var addr = results[0].address_components[i],
country1;
if (addr.types[0] == 'country')
country1= addr.long_name;
}
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng(),
country: country1
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
alert(ui.item.country);
$("#latitude").val(ui.item.latitude);
$("#longitude").val(ui.item.longitude);
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.