嗯,我目前正在将谷歌地图的一些功能移动到一个单独的文件中。在我的其他文件中,我创建了一些主要函数 search(),我在其中创建了包含其他文件的工作流。 我遇到的问题是 geocoder.geocode() 函数,直到今天它都运行良好,但我不知道出了什么问题。地理编码器被创建,然后跳过函数 geocoder.geocode() 而实际上没有做任何事情。有人有想法吗?
这是我的主要 file.js 的一部分:
//set the point.
var latlng = new google.maps.LatLng(55.379, -3.444);
//initialize the google map.
initializeMap(latlng, null, null, null);
//get selected country text from dropdown.
var address = $('#country option:selected').text();
//get entered postcode from textbox.
if ($("#postcode").val() != "") {
address = $('#postcode').val() + ", " + address;
}
//do a google search and store the result.
var result = googleSearch(address);
地址类似于:“NX5 897,美国”。 这是 functionCollection.js 中的 googleSearch
function googleSearch(address) {
var result;
//setting up a geocoder search.
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result = results[0];
}
else {
alert("Geocode was not successful for the following reason: " + status);
result = null;
}
});
return result;
}
最佳答案
您正在返回异步请求 geocoder.geocode() 的结果。 向 googleSearch 发送回调或仅从函数内部调用您的函数。
geocoder.geocode({ address: address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result = results[0];
}
else {
alert("Geocode was not successful for the following reason: " + status);
result = null;
}
somefunction(result); or callback(result)
});
关于JavaScript 地理编码不启动搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13028706/