dangerChihuahua007
dangerChihuahua007

Reputation: 20925

Why is this HTML5 geolocation-dependent javascript code erring?

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. ​

Upvotes: 1

Views: 423

Answers (2)

Talha
Talha

Reputation: 19282

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);

}

Upvotes: 2

dangerChihuahua007
dangerChihuahua007

Reputation: 20925

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.

Upvotes: 0

Related Questions