-1

Global variables defined outside function, but still they dont alert values outside scope? as i mentioned, first alert works (value assigned) but second one not.

 window.onload=getLocation();

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);


        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }

var lat;
var lng;

    function showPosition(position) {


      lat = position.coords.latitude.toFixed(3);
      lng = position.coords.longitude.toFixed(3);

        alert(lng); //alert done correctly

        var centerMap = new google.maps.LatLng(lat,lng);
        var directionsDisplay = new google.maps.DirectionsRenderer;
        var directionsService = new google.maps.DirectionsService;
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 14,
            center: centerMap
        });
        directionsDisplay.setMap(map);
         calculateAndDisplayRoute(directionsService, directionsDisplay);
        document.getElementById('mode').addEventListener('change', function() {
            calculateAndDisplayRoute(directionsService, directionsDisplay);
        });

    }

    alert(lng); //return nothing??
Fredi
  • 149
  • 3
  • 13
  • 2
    Who's calling `showPosition`? This is not enough of the code.... Having said that, the problem is likely that it's called asynchronously. That is, you outer alert runs before than the one inside `showPosition` – Ruan Mendes Feb 10 '17 at 20:48
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Aᴍɪʀ Feb 10 '17 at 20:49
  • call the function `showPosition` before outer `alert(lng);` or `lng` will remain `undefined` – Paweł Feb 10 '17 at 20:50
  • @Aᴍɪʀ I closed it initially, it's very likely that problem, but the question doesn't have enough info – Ruan Mendes Feb 10 '17 at 20:50
  • @JuanMendes you're right. Now that OP edited the question ... – Aᴍɪʀ Feb 10 '17 at 20:52
  • I added more code. – Fredi Feb 10 '17 at 20:52
  • 1
    @w3S My comment should tell you what the problem is. your outer alert is running before the alert inside `showPosition`. You have to move any code that relies on `lat, lng` so that it doesn't run until `showPosition` is called. Read http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call Others, I can't close it as a dupe because I closed/reopened it. Please vote to close. – Ruan Mendes Feb 10 '17 at 20:53
  • thanks all, also i'll check links and solutions... but why down-votes? @JuanMendes i get it. but i cant insert anything (that relay on `lat, lng`) inside one function. any way i will study about this type of functions. thanks. – Fredi Feb 10 '17 at 21:05
  • I'm newbie and down votes result on restrict me ask more questions... i dont think my question was stupid like that. anyway thank you SOF community for that.. – Fredi Feb 10 '17 at 21:23

1 Answers1

0

There are three problems, which I will address separately.

-

First - you are assigning window.onload incorrectly.

// This calls getLocation() and assigns the returned value to window.onload
window.onload=getLocation(); 

// This is what you intended - it assigns the function getLocation to window.onload, 
// which means getLocation will be called when the window finishes loading
window.onload=getLocation; 

-

Second, window.onload fires after all scripts have loaded. So even though you define window.onload=getLocation before you call alert(lng), the alert is going to run first because the window.onload event isn't triggered until after the script is loaded. You can test this by doing this:

window.onload = function() { console.log("window load function"); };
console.log("logging after window.onload is assigned");

You will observe that the second command is executed before the first.

If you want two things to happen one after another when the window is loaded, you can put them in the window.onload function like so:

window.onload = function () {
    getLocation();
    alert(lng);
};

Note, though, that in this particular case this still isn't enough because of item 3.

-

Third: navigator.geolocation.getCurrentPosition() is an asynchronous function. Your program keeps running while it waits for a position to be gotten, and then calls the callback you've defined for it. So even if you alert(lng) after the call to getLocation(), lng will still be NULL because getCurrentPosition hasn't triggered showPosition yet. To get all of this code to execute in the order you want, when the window has loaded, try the following:

window.onload = function () {
    getLocation(function () {
        alert(lng);
    });
};

function getLocation(callback) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function () {
            showPosition();
            callback();
        });
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

var lat;
var lng;

function showPosition(position) {


  lat = position.coords.latitude.toFixed(3);
  lng = position.coords.longitude.toFixed(3);

    alert(lng); //alert done correctly

    var centerMap = new google.maps.LatLng(lat,lng);
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var directionsService = new google.maps.DirectionsService;
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 14,
        center: centerMap
    });
    directionsDisplay.setMap(map);
     calculateAndDisplayRoute(directionsService, directionsDisplay);
    document.getElementById('mode').addEventListener('change', function() {
        calculateAndDisplayRoute(directionsService, directionsDisplay);
    });

}
AmericanUmlaut
  • 2,817
  • 2
  • 17
  • 27
  • that doesn't answer the question. – Aᴍɪʀ Feb 10 '17 at 20:58
  • @Aᴍɪʀ It did when the question was asked. The question was edited to add the fact that there was a callback that triggers showPosition(). – AmericanUmlaut Feb 10 '17 at 21:26
  • @AmericanUmlaut Like I commented in the other question, technically it did. But it was pretty clear that this was a callback that is called by the browser and the OP can't just call `showPosition`. If they could, then they already have position object. – Ruan Mendes Feb 10 '17 at 21:28
  • @JuanMendes Given the new information in the question I've updated the answer to address what I think are the main issues. – AmericanUmlaut Feb 10 '17 at 21:47
  • @Aᴍɪʀ I've updated my answer now that there is more information in the question – AmericanUmlaut Feb 10 '17 at 21:48