-1

I want to use "start" as a global variable for my starting point. So I declare it as a global variable and then set a value in the codeAdress function. The value is used to set a marker, which is working as expected. When I want to use the start variable in my calcRoute function it is undefined.

I'm using following code:

<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>
halfer
  • 19,824
  • 17
  • 99
  • 186
Philipp Rosengart
  • 713
  • 1
  • 8
  • 20

1 Answers1

2

You'll need to call calcRoute once start is set. And since start is set in the callback to the geocode API, you'll have to call calcRoute inside that callback, post setting start. Something like

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