I thought I was doing something fundamentally wrong. This weekend I went to a code camp meetup and the guy hosting it couldn’t figure out what I was doing wrong either. Could someone point me in the right direction as to why I’m not able to pull anything from the API? My codepen is here: https://codepen.io/rivid/pen/NamjLp
Whenever you encounter an issue, take a look at the developer tools to see what’s going on. Here, we can see this error was logged.
jquery.min.js:2 Uncaught ReferenceError: position is not defined
at HTMLDocument.<anonymous> (pen.js:13)
at j (jquery.min.js:2)
at k (jquery.min.js:2)
What does this mean? Well, it means that it can’t access the position variable. Let’ take a look at your code (I’ve indented it a little so it’s more clear).
navigator.geolocation.getCurrentPosition(function(position) {
$("#location").html("latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude);
});
var lat = position.coords.latitude;
The position is passed as an argument to .getCurrentPosition(). But the trouble is; that position disappears as soon as the function does. This means that position stops being defined for
var lat = position.coords.latitude;
You’ll probably want to move those statements into the function, then.