Problem with assigning current position to variable

Problem with assigning current position to variable
0

#1

Hi, I have got strange problem with something that seems very simple. Here is my codepen link http://codepen.io/leszczu/pen/mErqqd I try to get position of my current location and save it to variables. To check if it works I am passing variable “longitude” to html element with class “longitude”. If i run my program then alert message (line 19) shows that my variable is undefined but passes correct value to the html. However if I comment out the alert message value that is passed to html is undefined. Any idea what is going on?
regards
Tomasz


#2

So there are two issues. One, you have to use https from what I understand to use geolocation. So change your url to https://codepen.io.

Although you set your longitude variable first before appending it to a div, your longitude variable is still waiting to receive the actual geo data. By the time it receives it, append has already been called while longitude was still undefined.

So to get around that, you can either use a callback function or you can place your append in your showPosition function. (Also, you could leave your append where it is, but place it in a setTimeout function. Set the time to a second or so, and you should see that it works when you delay the append call)