How to add gelocation to global variable?

I want something like var lat = position.coords.latitude

 function getLocation() {
     if (navigator.geolocation) {
     } else { 
         document.getElementById("demo").innerHTML = "Geolocation is not supported by this browser.";
 function showPosition(position) {
     document.getElementById("demo").innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
 document.getElementById("btn").addEventListener("click", getLocation);

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


If you want a variable called lat to be accessible outside of the the showPosition function, then you will need to declare it in the global scope and then assign it a value from within the showPosition. That function is the only place where you will have access to the position response from the call to navigator.geolocation.getCurrentPosition.

Just keep in mind, that since navigator.geolocation.getCurrentPosition is asynchronous, lat will only have a value of undefined in the global scope until the actual response comes back from the API.

Thanks. I’ll keep it in mind.

But now I have CORS errors.
I’ve tried several proxies and it still doesn’t work.

I am getting a 401 error message of “Invalid API key. Please see for more info.” in the browser’s console (Ctrl+Shft+J in Chrome).

Make sure you have copied and pasted all of the API key given to you when you signed up for an openweathermap account.

Thanks. I’ve switched to the FCC weather API instead, but I’m still getting 401 error, and then CORS error on top. Is this common with these FCC projects?