I’m really struggling with basic Javascript here… basically, I’m trying to make a function that, when called, sets two variables (longitude and latitude) so that I can run other functions straight afterwards that uses these values.
When I try to alert out the longitude value however, it comes back undefined.
Here’s my code.
var latitude;
var longitude;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function displayLocation(position, latitude, longitude) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
return;
}
function newLocation(longitude) {
alert(longitude);
}
window.onload = function() {
getLocation();
newLocation();
}
Any help will be seriously appreciated! Thanks.
There are a few problems with the code you posted:
The arguments to
displayLocationare hiding your global variables. When you make the assignments here, you are actually assigning to your argument variables, which are in the local scope.IIRC, the callback to geolocation.getCurrentPosition only takes the first argument, so you shouldn’t have to define the
latitudeandlongitudeas arguments.Same problem in the
newLocationfunction. You call it without arguments, but thelongitudeargument is “hiding” the global variable.These are small syntax problems. However there is another problem in the code, which is a bit trickier to solve.
When the page is loaded, you call the two functions sequentially:
The second function,
newLocation, expects thatgetLocationhas set the global variables. This, however, may not be the case. When thegetLocationfunction callsgeolocation.getCurrentPosition, it’s performing an asynchronous operation. The next line after the call continues to execute immediately, but the callback functiondisplayLocationhas not necessarily been called yet. This can be a bit complicated to understand at first, but basically you need to only callnewLocationafterdisplayLocationhas run.So it gets complicated? That’s why it’s considered a good practice to try to avoid global variables altogether. Javascript often forces us to do asynchronous programming, and trying to understand all the possible states in which the global variables could be at any given time could drive you mad.
Instead, if possible, you should always use function arguments directly. For example in your scenario, you could skip the
displayLocationstep entirely, and go straight tonewLocation:So global variables are no longer needed.
I’m sure that the example code you posted is simplified, and your actual code is more complicated, but if you’re able to follow these principles, I think you’ll have a better time with javascript.