JavaScript变量为空

JavaScript variable empty

我想使用 "start" 作为我的起点的全局变量。所以我将其声明为全局变量,然后在 codeAdress 函数中设置一个值。该值用于设置按预期工作的标记。当我想在我的 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>

设置 start 后,您需要调用 calcRoute。由于 startgeocode API 的回调中设置,您必须在该回调中调用 calcRoute,post 设置 start.像

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