关于javascript变量的问题

时间:2014-02-24 15:09:31

标签: javascript global-variables google-geocoder

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <title>Geocoding service</title>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
        <script>
            function initialize() {

                geocoder = new google.maps.Geocoder();

                address = "toronto, canada";

                geocoder.geocode({
                    'address': address
                }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        var lat = results[0].geometry.location.lat();
                        var lng = results[0].geometry.location.lng();
                    } else {
                        var lat = 123;
                        var lng = 456;
                    }
                    document.getElementById('my_place1').value = lat + " - " + lng;
                });

                document.getElementById('my_place').value = lat + " - " + lng;

            }
        </script>
    </head>

    <body onLoad="initialize()">
        <input name="" id="my_place" style="width:300px; margin-left:20px;" type="text">
        <br>
        <input name="" id="my_place1" style="width:300px; margin-left:20px;" type="text">
    </body>
</html>

在上面的代码中my_place1值正在运行但是与my_place不相同的值。任何人都可以帮忙解决这个问题吗?我希望使用geocoder.geocodelat值来lng以外的地方工作。

2 个答案:

答案 0 :(得分:1)

您的document.getElementById('my_place').value = lat + " - " + lng ;latlang之前执行,这是异步的概念。

当你想在geocoder.geocode(之外使用它时,你必须在制作updatdateMyPlace()lat之后调用回调函数lang

<强>更新

 function initialize() {
      geocoder = new google.maps.Geocoder();
      address = "toronto, canada";
      geocoder.geocode({ 'address': address}, function(results, status) {

      if (status == google.maps.GeocoderStatus.OK) {
        var lat = results[0].geometry.location.lat();
        var lng = results[0].geometry.location.lng();
        }
      else {
         var lat = 123;
          var lng = 456;
       }
        document.getElementById('my_place1').value = lat + " - " + lng  ; 
        updatdateMyPlace(lat, lng);
     });

     function updatdateMyPlace(lat, lng){
        document.getElementById('my_place').value = lat + " - " + lng ; 
     }
 }

答案 1 :(得分:0)

您在本地确定这些值的范围,这意味着您只能在同一个块中访问它们。

if (status == google.maps.GeocoderStatus.OK) {

    var lat = results[0].geometry.location.lat();
    var lng = results[0].geometry.location.lng();

    document.getElementById('my_place1').value = lat + " - " + lng;

}  // <--- once you exit this block, the lat/lng no longer exist