… how to perform geolocation with JavaScript only (and a HTML 5 browser)

While  HTML 5 may not reach recommendation status for a few years, support for some feature will be available in browsers very soon.  I was recently asked to review some geolocation alternatives and here’s what I learned.

First, a basic sample.

<script>

   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition,showError);
   } else {
      alert('not available');
   }

   function showPosition(position) {
       alert(position.coords.latitude + " " + position.coords.longitude);
   }

   function showError(error) {
      alert("Error: " + error.code + " " + error.message);
   }

</script>

void getCurrentPosition(in PositionCallback successCallback);
void getCurrentPosition(in PositionCallback successCallback, in PositionErrorCallback errorCallback);
void getCurrentPosition(in PositionCallback successCallback, in PositionErrorCallback errorCallback, in PositionOptions options);

As you can see the getCurrentPosition()  function can accept 1, 2 or 3 parameters.  The first 2 are callbacks for success and error respectively.  The 3rd parameter can be used to adjust the required accuracy.  In addition there’s another function named watchPosition.  In that case, the success callback is called multiple times as the position changes.

The most important members of the Position object are latitude, longitude and accuracy.   These properties should be non-null for all implementations.  Other properties which may or may not be supplied based on the browers implementation include: altitude, altitudeAccuracy, heading and speed.

To see this work today, try the sample in Firefox 3.5 Beta 4.  For more detailed information, try to get through the current specification.

Advertisements

~ by Bob Banks on 06/07/2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: