Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Erin Potter
16,179 PointsJavaScript variables
I am writing an app that will update the weather based on the user's current position. Right now, I can't seem to access the new values of the variables lat, lon and url once I'm outside of the getLocation function, even though the variables were declared prior to that function. Maybe I've just been staring at this too long, but what am I missing here?
http://codepen.io/erincpotter/pen/eZOKzB
$(document).ready(function() {
var lat = 0;
var lon = 0;
var url = "";
var units = "imperial";
//get location
function getLocation(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
url = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&units=" + units + "&APPID=0f0c9c216df9e7530a502bea1122e161";
$("#weather").html("latitude: " + lat + "<br>longitude: " + lon);
} //end getLocation
navigator.geolocation.getCurrentPosition(getLocation);
console.log(lat);
console.log(lon);
console.log(url);
}); //end document.ready
2 Answers
V. T van der Vlugt
14,883 PointsHave you tried clearing your cache as i've copied your codepen to my workspace and it is working just fine. Below is a screenshot I took of the workspace:
grahammowat2
6,038 PointsYou could always create all your new functions within the getLocation function that way you can use the lat and lon variables wherever you like within the other functions.
Erin Potter
16,179 PointsThe thing is, I really have to be able to call the two functions separately. Since this is all part of an API request, the getLocation function sets my url, and the other function is the callback. So far, I've discovered that the problem is that getCurrentPosition is asynchronous, since it is dependent on the user's response (giving permission or not). Haven't figured out a way around it yet.
Erin Potter
16,179 PointsErin Potter
16,179 PointsSorry, I should have been clearer. What's displaying on the page is the values of the variables from within the getLocation function. The problem is that when I console.log the variables outside of the function, they revert to their original values. I need to use the updated values in another function.