2011-11-28 5 views
3

我正尝试使用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 
    ... 

回答

2

我猜你在异步地理编码函数完成之前正在查看点数组,并且实际上已将点放入数组中。

geocoder.geocode()函数可能是一个异步函数,您对codeAddress函数的调用只会启动该进程,并在一段时间后完成。这可以解释为什么drawLine()函数中的alert()没有看到任何点 - 它们还没有出现。当geoCode函数实际完成并调用它的回调时,它们将放入点数组中。

+0

“异步功能”...请不要混淆初学者与不存在的术语......“异步功能”在javascript中不存在。 – TMS

+0

异步函数是在你调用它时启动一个操作,立即返回,然后在一段时间后完成,通常在完成时调用某种完成函数。大多数Ajax调用以这种方式工作。这不是该语言的属性(我的意思并非如此),而是浏览器中大多数使用网络的操作都是如此。因此,当第一个函数调用返回时,您不能使用操作的结果,因为操作尚未完成。您必须等到完成回调被调用,表示操作已完成。 – jfriend00

+0

你解释了正确和正确的原则,但我建议不要使用术语“异步函数”,因为它讲述了某些不存在于javascript中的函数。不要定义新术语。 “功能”本身不是异步的。在某些情况下,我们可能会*调用整个操作“异步”,但也可能不是这种情况 - 我不会将每个回调传递为“异步操作”。它可能只是一些事件处理对象的正常初始化。 – TMS

0

可能的问题是您作为第二个参数传递给geocoder.geocode的回调函数尚未被调用。地理编码器可能刚刚存储它以便稍后在某个事件后调用它。将一些alert放入回调函数中,看它是否真的被调用!

... 
geocoder.geocode({ 'address': address, }, function (results, status) { 
     alert("CALLBACK CALLED!!"); 
     if (status == google.maps.GeocoderStatus.OK) { 
...