Firefox 3.5 makes it super simple to discover the location of a user on your website You can read more about it from Doug Turner or the official Mozilla page, but today I want to look at how to use the new API.
The following image is a screenshot of geolocation plus Google maps. If you’re running Firefox 3.5, we’ll replace that with a real map showing your current position.
First, we should check that the browser supports the Geolocation API:
if (!navigator.geolocation) { alert('Get a better browser'); }
Now that we’ve cleared out the riff-raff we can dive in to the new feature:
navigator.geolocation.getCurrentPosition()
I love the simplicity of this API; that’s all you need to know to get the user’s position! To do something useful, we’ll need a function to handle a successful positioning call:
navigator.geolocation.getCurrentPosition(function(position) {
alert(position.coords.latitude + ", " + position.coords.longitude);
});
Since it takes a few seconds to gather location data and send it up to the geolocation services, we must use an asynchronous callback instead of a return value.
The Position object has two fields: timestamp
and coords
. position.coords
holds all the position and velocity information, with the two most interesting (on my stationary desktop) being latitude
and longitude
. The motion information will be a lot more fun on mobile devices, especially in conjunction with navigator.geolocation.watchPosition.
This blog goes over the most basic usage of the geolocation API, but I have a slightly more involved example available at http://people.mozilla.com/~jbalogh/geo.html. If you view the source you can check out geolocation
, -moz-border-radius
, and -moz-box-shadow
in action.
NOTE: due to a bug in the current Firefox 3.5b4, the geolocation services may fail on repeated calls. The bug has been fixed, but we’re stuck with it in the current release.
Cato wrote on :
Ray R wrote on :
bcrowder wrote on :
Ka-Hing Cheung wrote on :
David wrote on :
steve wrote on :
Frédéric Wenzel wrote on :
RH wrote on :
Mark Gosdin wrote on :
Frédéric Wenzel wrote on :
Matt wrote on :
Florin Negoita wrote on :
sri wrote on :
Mr. T wrote on :
KS wrote on :
toupil wrote on :
Leif Harmsen wrote on :