1

I have some javascript code depending on geolocation.

http://jsfiddle.net/8D6vz/

var myLat = 0.0;
var myLng = 0.0;

function setCurrentPosition(position) {
 myLat = position.coords.latitude;
 myLng = position.coords.longitude;
}

function errorOccured() {
 document.write("sorry, error occured :( ");
}

$(function() {
 navigator.geolocation.getCurrentPosition(setCurrentPosition, errorOccured);
 document.write(myLat + " " + myLng);
});

However, this code merely produces

0 0

instead of

"client's latitude here" "client's longitude here"

Why?

I am using Google Chrome, which surely supports geolocation. I also allowed my browser to track my location. ​

0

2 Answers 2

2

GetCurrentPosition is an asynchronous function, and you can use it like

function GetGeolocation() {

navigator.geolocation.getCurrentPosition(GetCoords, GetError);

}
function GetCoords(position){

  var lat = position.coords.latitude;

  var long = position.coords.longitude;

  var accuracy = position.coords.accuracy;

  alert('Latitude: ' + lat + ', Longitude: '+ long);

}
Sign up to request clarification or add additional context in comments.

Comments

0

Oh, I think I figured it out.

I believe that

navigator.geolocation.getCurrentPosition()

is an asynchronous function. Hence, setCurrentPosition(position) is called after the latitude and longitude values are printed on the screen, which prints the original values.

1 Comment

Well, that was awkward. I answered my own question. I hope this question helps others who have stumbled over similar issues :) Also, let me know if you have a better answer or explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.