SO - 17214486
by spadez
HTML
<script src="http://maps.google.com/maps/api/js?sensor=true&libraries=places&.js"></script>
<h1>Form</h1>
<form id="geocode_form">
<input id="geokeyword" placeholder="Keyword" type="text" />
<input id="loc" placeholder="Location" type="text" />
<br />
<input class="hidden" id="ctry" disabled="true" value="us" />
<input class="hidden" id="lat" disabled="true" />
<input class="hidden" id="lng" disabled="true" />
<input type="submit" value="Geocode + Submit" class="button" id="search" />
<input type="submit" value="Geocode" class="button" id="geosearch" />
</form>
CSS
h1 {
font-size: 1.2em;
margin: 1em 0 1.2em;
}
p {
font-size: 0.8em;
font-weight: bold;
margin-bottom: 2em;
}
JavaScript
$(function () {
var lastQuery,
lastResult, // new!
autocomplete,
processLocation = function (callback) { // accept a callback argument
var input = $("#loc"),
lat = $("#lat"),
long = $("#lng");
var query = $.trim(input.val()),
geocoder;
// if query is empty or the same as last time...
if (!query || query === lastQuery) {
if (callback) {
callback(lastResult); // send the same result as before
}
return; // and stop here
}
lastQuery = query; // store for next time
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());
long.val(results[0].geometry.location.lng());
lastResult = true; // success!
} else {
alert("We couldn't find this location. Please try an alternative");
lastResult = false; // failure!
}
if (callback) {
callback(lastResult); // send the result back
}
});
},
ctryiso = $("#ctry").val(),
options = {
types: ["geocode"]
};
if (ctryiso !== '') {
options.componentRestrictions = {
'country': ctryiso
};
}
autocomplete = new google.maps.places.Autocomplete($("#loc")[0], options);
google.maps.event.addListener(autocomplete, 'place_changed', processLocation);
$('#search').on('click', function (e) {
var form = $(this).closest('form');
e.preventDefault(); // stop the submission
processLocation(function (success) {
if...