Geolocation + Accessing the data

I am having trouble passing the Geolocation latitude and longitude returned to my API search query. I am unsure how to access the var lat, var lon outside of the function. I think I have huge holes in my basic understanding of JavaScript and have been trying to figure this out for over a week now.

Above is a link to my CodePen. Please check it out to see the issue I am having.

It’s not a delay, I am just not sure how to pass the lat or lon into my search… please take a look, I am completely flummoxed and running out of ideas.

In order to access the lat and lon variable, you need to initialize them outside the function first. When you do it inside the function, they become local variables which can only be accessed inside the function where you created them.

Simply create them outside the function, and then set their values inside the function, and you should be able to access them.

Something like this:

var lat;
var lon;

function successFunction(pos){
lat = pos.coords.latitude;
lon = pos.coords.longitude;
}

Notice how the var keyword is missing in front of the variables inside the function. That’s because they’ve already been initialized earlier.

1 Like

I see what you’re saying and I have tried that. All it returns then is ‘undefined’. Essentially it stops alerting the lat and lon

Really appreciate the help but you mention that my issue is a delay problem, however I don’t believe it is? I kind of want to understand what is going in without copying your code… Sorry if this doesn’t make any sense

Hmm, that sounds strange, they should be defined. Do you still have the code where you tried it?

Your problem is codepen is not allowing you access … if you hit run above you see all the info is given.
and if you copy and paste code to notepad and open file in browser it works

these dont work though
x.innerHTML(‘It seems like Geolocation is not enabled.’);
as it should be … x.innerHTML = ‘It seems like Geolocation is not enabled’

Yes, the codepen in the title :slight_smile:

Nice spot on the innerHTML part.

But codepen does allow it to run as I can alert it in the function? I have HTTPS as i know it can’t run in HTTP