我是 JavaScript 新手。我一直在尝试设计一些代码,这些代码在点击搜索按钮时对位置进行地理编码,如果成功则提交表单。为了让它稍微复杂一点,如果选择了自动建议中的一个选项,它甚至在点击搜索按钮之前也会对其进行地理编码。
这一切似乎都有效,除了表单从未提交,我不知道为什么。
链接:http: //jsfiddle.net/sR4GR/42/
$(function () {
var input = $("#loc"),
lat = $("#lat"),
lng = $("#lng"),
lastQuery = null,
lastResult = null, // new!
autocomplete;
function processLocation(query, callback) { // accept a callback argument
var query = $.trim(input.val()),
geocoder;
// if query is empty or the same as last time...
if( !query || query == lastQuery ) {
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());
lng.val(results[0].geometry.location.lng());
lastResult = true; // success!
} else {
alert("Sorry - We couldn't find this location. Please try an alternative");
lastResult = false; // failure!
}
callback(lastResult); // send the result back
});
}
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(); // stop the submission
processLocation(function (success) {
if( success ) { // if the geocoding succeeded, submit the form
form.submit()
}
});
});
});