sogo
sogo

Reputation: 351

Javascript variable scoping issue in geocoding

When I use Geocoding APIs on my code, I assigned var latitude as an global(line 20), and in function geocoder, variable works. But in line 35, it throws out error as 0. Even though it works in function scope.

14 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
15 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
16 <script type="text/javascript">
17 
18 var geocoder = new google.maps.Geocoder();
19 var longitude = 0.0;
20 var latitude = 0.0;
21 
22 if (geocoder) {
23     geocoder.geocode({ 'address': 'Louvre Museum' }, function (results, status) {
24             if (status == google.maps.GeocoderStatus.OK) {
25             longitude = results[0].geometry.location.nb;
26             latitude = results[0].geometry.location.ob;
27             console.log(results[0].geometry.location);
28             } 
29             else {
30             console.log('No results found: ' + status);
31             }
32             });
33 }
34 
35 console.log(latitude);

Upvotes: 0

Views: 75

Answers (1)

putvande
putvande

Reputation: 15213

The Geocoder works asynchronous, so when you call console.log(latitude) the Geocoder hasn't finished yet and therefor not assigned a different value to latitude.

https://developers.google.com/maps/documentation/geocoding/

To display your coordinates you could do something like:

    geocoder.geocode({
    'address': 'Louvre Museum'
}, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        longitude = results[0].geometry.location.nb;
        latitude = results[0].geometry.location.ob;
        console.log(results[0].geometry.location);
        document.getElementById('the_id_of_your_element').innerHTML = longitude + ',' + latitude;
    } else {
        console.log('No results found: ' + status);
    }
});

Upvotes: 1

Related Questions