I managed to get a jquery script that will geocode a typed location through googles geocoding system.
I need to indicate the short name of the country, placed in the country field. For life, I cannot understand how I should integrate, and everything I try does not return a value. Can someone please give an idea of the right way to achieve this?
JSFIDDLE: http://jsfiddle.net/spadez/jCB4s/2/
$(function () {
var input = $("#loc"),
lat = $("#lat"),
lng = $("#lng"),
lastQuery = null,
lastResult = null,
autocomplete;
function processLocation(callback) {
var query = $.trim(input.val()),
geocoder;
if( !query || query == lastQuery ) {
callback(lastResult);
return;
}
lastQuery = query;
geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: query }, function(results, status) {
if( status === google.maps.GeocoderStatus.OK ) {
lat.val(results[0].geometry.location.lat());
lng.val(results[0].geometry.location.lng());
lastResult = true;
} else {
alert("Sorry - We couldn't find this location. Please try an alternative");
lastResult = false;
}
callback(lastResult);
});
}
autocomplete = new google.maps.places.Autocomplete(input[0], {
types: ["geocode"],
componentRestrictions: {
country: "uk"
}
});
google.maps.event.addListener(autocomplete, 'place_changed', processLocation);
$('#searchform').on('submit', function (event) {
var form = this;
event.preventDefault();
processLocation(function (success) {
if( success ) {
form.submit()
}
});
});
});
According to the API, I need the following:
results[]: {
types[]: string,
formatted_address: string,
address_components[]: {
short_name: string,
long_name: string,
types[]: string
},
geometry: {
location: LatLng,
location_type: GeocoderLocationType
viewport: LatLngBounds,
bounds: LatLngBounds
}
}
Jimmy source
share