-
Notifications
You must be signed in to change notification settings - Fork 68
places.js
Calin Rada edited this page Oct 16, 2013
·
1 revision
This page is an example of how to use Google API to search for a city:
function initialize(theElement) {
var input = (document.getElementById(theElement));
var autocomplete = new google.maps.places.Autocomplete(input, {types: ['(cities)']});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
var itemRoute='';
var itemLocality='';
var itemCountry='';
$.each(place.address_components, function (i, address_component) {
if (address_component.types[0] == "locality"){
//console.log("town:"+address_component.long_name);
itemLocality = address_component.long_name;
}
if (address_component.types[0] == "country"){
//console.log("country:"+address_component.long_name);
itemCountry = address_component.long_name;
}
});
var toSave = {
'latitude': place.geometry.location.lat(),
'longitude': place.geometry.location.lng(),
'formatted_address': place.formatted_address,
'city': itemLocality,
'country': itemCountry,
}
console.log(place);
$.post(app.api_url + 'location/save', toSave, function(data){
if($('#'+theElement+'_id').length > 0) {
$('#'+theElement+'_id').val(data.id);
}
}, 'json');
});
}
google.maps.event.addDomListener(window, 'load', initialize('home_location'))
google.maps.event.addDomListener(window, 'load', initialize('current_location'))