HTML5 GeoLocation API - no callback is called what

2020-06-28 15:10发布

问题:

I have a code snippet that checks for GeoLocation API. If it's available, I try to get current position. But depending on the browser, code works differently:

  • in IE, successCallback is called with every F5 refres
  • in FF, I get successCallback or errorCallback with error code = 2 (POSITION_UNAVAILABLE)
  • in Chrome I get successCallback or... nothing. I wait and wait and nothing

Actually I need successCallback to be called in some consistent manner... Is there a change to achieve it?

Code snippet:

function successCallback(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    alert("Your location is: " + latitude + "," + longitude);
}

function errorCallback(error) {
    console.log(error);
}

if (Modernizr.geolocation) {
    navigator.geolocation.getCurrentPosition(successCallback, errorCallback, { maximumAge: 0 });
    alert("geolocation is enabled");
} else {
    alert("geolocation is NOT enabled");
}

Quick note 1:

alert("geolocation is enabled");

is called every time.

Quick note 2:

setting:

maximumAge: 1

works better. Now Chrome & IE call successCallback every time. Only FF freaks me out, it calles successCallback randomly.

回答1:

Not much you can do about this. You're at the whim of the browser developers and how they attempt to figure out your location based on WiFi Access Point fingerprinting, or IP lookup.

Out of curiosity, I tested the code (http://jsfiddle.net/YbtSZ/2/) on the following browsers and found it worked inconsistently.

Mac 10.7.2

  • Chrome on Mac - works
  • FF 9 on Mac - works
  • Safari on Mac - does NOT work

XP native

  • FF 9 on XP - works
  • IE 8 on XP - does NOT work (Geolocation NOT supported)

XP running virtualised in Mac

  • Chrome on XP (virtualised in Mac) - does NOT work (POSITION UNAVAILABLE)
  • FF 9 on XP (virtualised in Mac) - does NOT work (POSITION_UNAVAILABLE)
  • IE 8 on XP (virtualised in Mac) - does NOT work (Geolocation NOT supported)


回答2:

You might want to try Modernizr, it's a JavaScript library that abstracts away HTML5 features so you get consistent results. Check out the docs for more information.



标签: geolocation