stank345 stank345 - 2 months ago 34
Javascript Question

navigator.geolocation.getCurrentPosition() doesn't work

I am trying to get the latitude and longitude of my current location using geolocation. Extremely similar code was working until recently, and I can't figure out why it stopped working. It is no longer setting the variables latitude or longitude. When I walk through the js code, the getCurrentPosition() method is skipped and I'm not sure why. Bizarrely, if I put an alert box in the getCurrentPosition() method, it will get and display the latitude and longitude correctly... I have no idea why it does that.

var gl;
try {
if (typeof navigator.geolocation === 'undefined'){
gl = google.gears.factory.create('beta.geolocation');
} else {
gl = navigator.geolocation;
} catch(e) {}

var latitude;
var longitude;

if (gl) {
function (position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
//alert("got the lat & long - lat=" + latitude + ", lng=" + longitude);
function (error) {
alert("Error getting geolocation:" + error);
} else {
alert("Geolocation services are not supported by your web browser.");

I then go on to set some markers on a map using the Google Maps API.

Thank you very much,



Here the code on JSFiddle showing the weird behavior:


I just tried your jsfiddle and it worked fine (Chrome 19 on Win 7), so I can't see why it should be causing problems.

Having said that, I'd strongly recommend switching to use navigator.geolocation.watchPosition instead of navigator.geolocation.getCurrentPosition. I recently did some work on a geolocation system and found getCurrentPosition can return unreliable cached positions, even if you use the options parameter to specify a low maximumAge value.

My latest version stops the watch after one of the following is true:

  • the fifth position has been returned
  • the accuracy is under 100m
  • the time since the watch began is over 30 seconds