我很难受。这是我正在使用的代码:
http://jsfiddle.net/arunpjohny/Jfdbz/
$(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());
long.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);
});
});
单击自动建议链接时,它应该对第一个和第二个示例中的结果进行地理编码。但是,当我从下拉列表中单击自动建议选项时,我在第 39 行收到以下错误:
未捕获的类型错误:无法调用未定义的方法“val”
任何人都可以帮助查明我在这里出错的地方吗?
编辑:要复制我执行以下操作:
- 在 Chrome 中打开 javascript 控制台
- 在顶行的位置框中输入几个字母
- 从下拉菜单中单击建议的位置
显然根据我的编辑第 39 行是这样说的:
if (ctryiso !== '') {