1

I am trying to overwrite a variable but somehow it's not working. What am I doing wrong here?

    var url = 'BB';

    navigator.geolocation.getCurrentPosition(function (position) {
        url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude.toString() + ',' + position.coords.longitude.toString();
    });

    console.log(url);

shouldn't my url get the whole string instead of output bb?

Tsuna
  • 2,098
  • 6
  • 24
  • 46

2 Answers2

4

It's because navigator.geolocation.getCurrentPosition is asynchronous and console.log(url) gets executed before your callback function in which you overwrite url

This thread might help if you aren't familiar with asynchronous execution:

Asynchronous vs synchronous execution, what does it really mean?

Community
  • 1
  • 1
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
0

As Adam pointed out, you're trying to use the url variable before it gets assigned a value (other than the 'BB' you initialize it with).

Unless you have a good reason to make the url variable global and understand the issues around asynchronous code, it is best if you do not declare this variable outside the callback. This leads to the kind of trouble you ran into.

Instead, declare url right where you assign it, inside the callback. And then do whatever you need to do with it inside the callback, or in a function you call from inside the callback. Do not attempt to use it as a global variable.

For example, this would work without having the problem you ran into:

navigator.geolocation.getCurrentPosition(function (position) {
    var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude.toString() + ',' + position.coords.longitude.toString();
    console.log(url);
});
Michael Geary
  • 28,450
  • 9
  • 65
  • 75
  • "One thing you should definitely do here is not declare the url variable outside the callback." - I think that really depends on what you're ultimately trying to do. The OP hasn't provided enough information to let anybody make the certain judgement as to whether he should or shouldn't declare URL outside the callback. – Adam Jenkins Feb 15 '17 at 02:00
  • @Adam That's a good point. Perhaps I should say "unless you really know what you're doing and have a good reason for it, don't declare `url` outside the callback." After all, declaring it outside the callback and trying to use it outside the callback is what led to the trouble. – Michael Geary Feb 15 '17 at 02:02