About Geolocation in HTML 5

Alix Axel picture Alix Axel · Feb 11, 2010 · Viewed 11.4k times · Source

Google Maps can now pinpoint my location with street precision with the help of Firefox.

I understand this is a new feature of HTML 5 compatible browsers and that the location is fetched by using some sort of feature of the connected WiFi network (I hope I'm not making any silly assumptions).

What I intend to know is how this whole process exactly works:

  • Why only in HTML 5?
  • Why / how does Firefox ask me to share my location with Google Maps?
  • What is the normal precision one can count on?
  • How can I implement this feature in my websites?

Thanks in advance!

Answer

Daniel Vassallo picture Daniel Vassallo · Feb 12, 2010

How does it work?

When you visit a location-aware website in Firefox, the browser will ask you if you want to share your location.

If you consent, Firefox gathers information about nearby wireless access points and your computer’s IP address, and will get an estimate of your location by sending this information to Google Location Services (the default geolocation service in Firefox). That location estimate is then shared with the requesting website. (Source)

How accurate are the locations?

Accuracy varies greatly from location to location. In some places, the geolocation service providers may be able to provide a location to within a few meters. However, in other areas it might be much more than that. All locations are to be considered estimates as there is no guarantee on the accuracy of the locations provided. (Source)

In my case, Firefox reports that I am about 10km away from my real location.

How do I use this feature in my website?

You would do something like this:

if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(function(position) {  

        alert(position.coords.latitude + ", " + position.coords.longitude);

        // Use the latitude and location as you wish. You may set a marker
        // on Google Maps, for example.
    }); 
} 
else {
    alert("Geolocation services are not supported by your browser.");
}  

You can see an online demo here: Firefox HTML 5 Geolocation Demo (Requires a geolocation-aware browser such as Firefox 3.1b3.)