JavaScript - 全局变量显示为未定义

时间:2013-05-13 20:42:51

标签: javascript google-maps-api-3 global-variables undefined geocoding

关于这个话题有很多线索,但我仍然无法为我的案例找到合适的答案......

这是我正在尝试做的事情:

1)使用Google Maps API v3定义一个获取地理编码的功能

2)使用相关地址调用函数以获取此特定地址的地理编码

如果我放置

,代码完全正常
    alert(address); 

    address = results[0].geometry.location;

由于我需要它作为全局变量,遗憾的是这不是一个选择。当试图将'address'变量用作全局函数时,我总是得到值'undefined'。

<!DOCTYPE html>
<html>
<head>
  <script src="http://maps.googleapis.com/maps/api/js?sensor=false"
      type="text/javascript"></script>
</head>

  <script type="text/javascript">
    var geocoder;
    var address;

     address = 'Frankfurt, Germany';

  function codeAddress() {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {

address = results[0].geometry.location;


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

codeAddress(address);
alert(address);

  </script>


</body>
</html>

有人能帮我这个吗?盯着代码似乎并没有把我带到任何地方。 我感谢所有可用的帮助,谢谢!

2 个答案:

答案 0 :(得分:0)

问题是geocode 异步,没有?

这意味着在“稍后某个时间点”调用地理编码回调,这是首次调用原始帖子中的外部更改之后。 (它不应该警告undefined,因为它首先设置为特定的字符串,所以我忽略了该语句。)

function codeAddress() {
  geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      // Only use address *after the callback success* and get rid of
      // the global variable if possible - note how it's just passed here.
      // You can use `debugger;` to stop here and check the value to
      // make sure it is set as appropriate.
      var address = results[0].geometry.location;
      alert(address);
      doOtherStuffWithAddress(address);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

function doOtherStuffWithAddress (address) {
   // don't need no stinking globals
}

请参阅How to return the response from an AJAX call?

  

AJAX中的A代表异步。这意味着发送请求(或者更确切地说是接收响应)将从正常执行流程中取出。在您的示例中,$ .ajax立即返回,并且在您传递的函数之前执行下一个语句return result;,甚至调用成功回调。

专门针对上下文:

  

地理编码功能是异步的。这意味着发送请求(或者更确切地说是接收响应)将从正常执行流程中取出。在您的示例中,geocode立即返回,并且在您作为成功回调传递的函数被调用之前执行下一个语句alert(address)。

答案 1 :(得分:0)

谢谢你的回答。我现在能够完成我的项目!在下面找到我的最终代码。代码填充地址数组的地理编码。玩得开心。

<!DOCTYPE html>
<html>
<head>
  <script src="http://maps.googleapis.com/maps/api/js?sensor=false"
          type="text/javascript"></script>
</head>
<BODY>
<DIV ID="pro"></div>
<DIV ID="adr"></div>

  <script type="text/javascript">
    var geocoder;




var addresses = "Berlin, Deutschland; Frankfurt, Deutschland; Broadway Street, New York City, New York, USA";


 geocoder = new google.maps.Geocoder();

var address = addresses.split(';');

var i = 0;
var timeout = 600;


codeAddress(i);


function codeAddress(i) {


    geocoder.geocode( { 'address': address[i]}, function(results, status) 
    {
            if (status == google.maps.GeocoderStatus.OK) {
            document.getElementById("adr").innerHTML = document.getElementById("adr").innerHTML + "<BR>{location: new google.maps.LatLng" + results[0].geometry.location + ", weight: 1},";

                                } else {
                if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
                    {
                        setTimeout(function() { addMarker(position); }, (timeout * 3));
                    }
                                        }


i++;
var percent = ((i) / address.length) * 100;
percent = percent.toFixed(2);
percent = percent + " %";
document.getElementById("pro").innerHTML = percent; 


if (i < address.length)
        {
            setTimeout(function() { codeAddress(i); }, (timeout));
         }

    });



            }

</script>


</body>
</html>