How to add gelocation to global variable?

How to add gelocation to global variable?
0

#1

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

 function getLocation() {
     if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(showPosition);
     } 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);

#2

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.


#3

Thanks. I’ll keep it in mind.

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


#4

I am getting a 401 error message of “Invalid API key. Please see http://openweathermap.org/faq#error401 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.


#5

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?