我正尝试使用Google地图JavaScript API在两点之间绘制一条线。这两点需要进行地理编码(转换为google.maps.LatLong对象),然后才能用于绘制线条。添加到全局数组变量的项不会在添加函数之外持久
地理编码功能是codeAddress,当它返回时,它调用回调函数,将新的latlong添加到名为points的全局数组中。出于某种原因,添加到点的值不会保留在数组之外。我相对较新的JavaScript,所以我不能告诉什么可能是错的,任何想法将不胜感激!
var points = new Array();
function addGeocodedLatLongToGlobalList(address) {
points.push(address);
alert("added a point " + points[0]); // correctly outputs latlong object
}
function codeAddress(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address, }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
addGeocodedLatLongToGlobalList(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function drawLine(address1, address2, color) {
codeAddress(address1);
codeAddress(address2);
alert("there is a point " + points[0]); //now the points[0] value is undefined
...
“异步功能”...请不要混淆初学者与不存在的术语......“异步功能”在javascript中不存在。 – TMS
异步函数是在你调用它时启动一个操作,立即返回,然后在一段时间后完成,通常在完成时调用某种完成函数。大多数Ajax调用以这种方式工作。这不是该语言的属性(我的意思并非如此),而是浏览器中大多数使用网络的操作都是如此。因此,当第一个函数调用返回时,您不能使用操作的结果,因为操作尚未完成。您必须等到完成回调被调用,表示操作已完成。 – jfriend00
你解释了正确和正确的原则,但我建议不要使用术语“异步函数”,因为它讲述了某些不存在于javascript中的函数。不要定义新术语。 “功能”本身不是异步的。在某些情况下,我们可能会*调用整个操作“异步”,但也可能不是这种情况 - 我不会将每个回调传递为“异步操作”。它可能只是一些事件处理对象的正常初始化。 – TMS