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