我在剧本上遇到了困难。这是它应该做的:
当按下地理编码并提交按钮时,它将执行以下操作(这已经有效):
当按下地理编码按钮时,我希望它执行以下操作(这不起作用):
所以我的问题是,我怎样才能这样做,这样我就可以为两个脚本使用相同的代码,而不必重复两次。我的想法是做以下事情:
http://jsfiddle.net/spadez/XyCF9/1/
$(function () {
var lastQuery = null,
lastResult = null, // new!
autocomplete,
processLocation = function (input, lat, long, 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) {
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());
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!
}
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').click(function (e) {
var form = $(this).closest('form'),
input = $("#loc"),
lat = $("#lat"),
lng = $("#lng");
e.preventDefault(); // stop the submission
processLocation(input, lat, lng, function (success) {
if (success) { // if the geocoding succeeded, submit the form
form.submit();
}
});
});
$('#geosearch').click(function (e) {
var form = $(this).closest('form'),
input = $("#geoloc"),
lat = $("#geolat"),
lng = $("#geolng");
e.preventDefault(); // stop the submission
processLocation(input, lat, lng);
});
});
我现在得到的错误是:
任何人都可以了解我的错误吗?
答案 0 :(得分:2)
变量名称为long
而非lng
lat.val(results[0].geometry.location.lat());
long.val(results[0].geometry.location.lng());
演示:Fiddle
答案 1 :(得分:1)
试试这个......
$(lat).val(results[0].geometry.location.lat());
$(lng).val(results[0].geometry.location.lng());