Javascript 从google地理编码api获取latLong

Javascript 从google地理编码api获取latLong,javascript,google-maps-api-3,global-variables,google-geocoder,Javascript,Google Maps Api 3,Global Variables,Google Geocoder,我正在尝试使用Google Geocoding API从地址中获取纬度和经度。我想将坐标存储在一个变量中,以便以后使用。我知道这是一个异步调用。在下面的代码中,我尝试使用函数useCordinates将坐标分配给一个全局变量,以便以后可以使用它。但我没有调试时并没有定义获取cordinates。我是javascript新手。我在某个地方读到,不需要定义隐含的全局变量 myGlobalVar='你好,世界'; 谢谢你的帮助 function codeAddress(address){ var

我正在尝试使用Google Geocoding API从地址中获取纬度和经度。我想将坐标存储在一个变量中,以便以后使用。我知道这是一个异步调用。在下面的代码中,我尝试使用函数useCordinates将坐标分配给一个全局变量,以便以后可以使用它。但我没有调试时并没有定义获取cordinates。我是javascript新手。我在某个地方读到,不需要定义隐含的全局变量

myGlobalVar='你好,世界'; 谢谢你的帮助

 function codeAddress(address){
  var loc=[];
  geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
     // no need to define it in outer function now
    loc[0]=results[0].geometry.location.lat();
    loc[1]=results[0].geometry.location.lng();

    useCordinates( loc ); 

  } else {
    alert("Geocode was not successful for the following reason: " + status);
  }
});
}

function useCordinates(cordinateArray){
 cordinates= cordinateArray;
  }
functionTestCodeAddress(){
 start = document.getElementById('start').value;
 codeAddress(start);
 //assign the global variable 'cordinates'
 document.getElementById('start').value=cordinates; 
}

问题不在于变量,而在于尝试访问变量时的问题

目前,您在调用codeAddress()之后立即在TestCodeAddress()中执行此操作,因为此时异步请求尚未完成,所以这已经太早了

例如,您可以移动此行:

document.getElementById('start').value=cordinates; 
进入
useCordinates()