代码之家  ›  专栏  ›  技术社区  ›  Philipp Rosengart

JavaScript变量为空[重复]

  •  -1
  • Philipp Rosengart  · 技术社区  · 9 年前

    我想使用“start”作为全局变量作为起点。所以我将其声明为全局变量,然后在CodeAddress函数中设置一个值。该值用于设置标记,该标记按预期工作。当我想在calcRoute函数中使用start变量时,它是未定义的。

    我使用以下代码:

    <script>
                var map;
                var uluru;
                var start; <-- Declaration
                var geocoder;
    
                function codeAddress() {
                    var address = "Essen";
                    geocoder = new google.maps.Geocoder();
                    geocoder.geocode({
                        'address': address
                    }, function(results, status) {
                        if (status == 'OK') {
    
                            start = results[0].geometry.location; <-- Setting value
                            
                            var marker = new google.maps.Marker({
    
                                position: start,
                                map: map
                            }); <-- Position is set, start has a value
                        } else {
                            alert('Geocode was not successful for the following reason: ' + status);
                        }
                    });
    
                    calcRoute();
                }
    
                function calcRoute() {
                    var directionsService = new google.maps.DirectionsService;
                    var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
                    directionsService.route({
                        origin: start, <-- start is undefined
                        destination: uluru,
                        travelMode: 'DRIVING'
                    }, function(response, status) {
                        if (status === 'OK') {
                            directionsDisplay.setDirections(response);
                        } else {
                            window.alert('Directions request failed due to ' + status);
                        }
                    });
                }
    
            </script>
    1 回复  |  直到 9 年前
        1
  •  2
  •   maazadeeb    9 年前

    你需要打电话 calcRoute 一旦 start 开始 在回调中设置为 geocode 卡尔克劳特 在回调中,post设置 开始 .类似于

    geocoder.geocode({address: address}, function(results, status) {
      if (status == 'OK') {  
        start = results[0].geometry.location;
        // do the rest
        calcRoute();
      }
    });