0

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);
0

1 Answer 1

1

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);
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

Then how should I solve this problem? When I moved brace '}' to end of line, it didn't work also.
In the function where you defined the latitude is the first moment you can use the value. What is it you are trying to do with it?
I tried to find a specific geographic position, in this case Louvre, and print out message its coordination.
I have updated my answer. See if you can do something with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.