Aug 25

Using the W3C Geolocation API Specification today; Extending WhereAreYou

Ajax, Gears, Tech with tags: , , 4 Comments »

Last week I shared the WhereAreYou? application that used the Ajax APIs ClientLocation API to access your location via your IP address.

At the same time, we announced support for the Gears Geolocation API that can calculate your address using a GPS device, WiFi info, cell tower ids, and IP address lookups.

Add to all of that, the W3C Geolocation API that Andrei Popescu of the Gears team is editing. You will notice that it looks similar to the Gears API, with subtle differences. The ClientLocation API is quite different.

To make life easier, I decided to put together a shim called GeoMeta that give you the W3C Geolocation API, and happens to use the other APIs under the hood.

If you have the Geolocation API native in your browser (no one does yet, future proof!) that will be used. If you have Gears, that API will be used, and finally, with nothing the ClientLocation API will be used behind the scenes.

To you the API will look similar:

// navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options)
navigator.geolocation.getCurrentPosition(function(position) {
      var location = [position.address.city, position.address.region, position.address.country].join(', ');
      createMap(position.latitude, position.longitude, location);
}, function() {
      document.getElementById('cantfindyou').innerHTML = "Crap, I don't know. Good hiding!";
});

At least, that is what I would like. Unfortunately, there are a few little differences that leak through.

  • The W3C API only seems to give you a lat / long, so you have to do the geocoding to get address info
  • The Gears API gives you an additional gearsAddress object attached to the resulting position object. This can contain a lot of information on the resulting area (street address to city to …) however for certain providers the API returns that as null, the same as the W3C standard
  • That gearsAddress object has slightly different information from the address data that the ClientLocation API returns.

To give you control when you need it, you can ask the navigator.geolocation object what type it is. navigator.geolocation.type will be null if it is native, but ‘Gears’ or ‘ClientLocation’ if a shim kicks in. You can also check navigator.geolocation.shim to see if it is augmented code.

Implementation

There is some fun implementation code in there if you poke around. For example, for the ClientLocation API, when you make a call, it will be added to a queue if the Google Loader hasn’t fully loaded yet, and it will kick off that call when finished. Dealing with dynamically creating <script src> as a loading mechanism sure is fun!

I like the idea of jumping straight to the W3C standard and updating the shim as the APIs change. That way, when browsers catch up, the code will still work using the native APIs and you don’t have to change a thing.

Where are you?

Aug 22

Where are you? Using the new Ajax ClientLocation API

Ajax, Gears, Google, Mobile, Tech with tags: , 22 Comments »

We just announced two new ways to get location info from a browser client.

The Gears GeoLocation API is very detailed. It is able to use GPS, cell towers, WiFi, and ip addresses to work out the location, and you get an “accuracy” parameter to see what was available. As well as getting a position, you can watch a position so you are updated when a change happens. This is perfect for mobile devices that have Gears installed, and since the community is working on the W3C Geolocation spec it should be in many more places soon.

To go with the Gears API, we also have an API that goes along with the AJAX APIs, called ClientLocation.

This is an ip based geocoder that we have made available, and is very simple.

I put together a trivial example called Where Are You? that ties together this API with the Maps API:

You get access to the data from google.loader.ClientLocation, which is null if it can’t be calculated.

Here is a bit of JavaScript that ties it together:

google.load("maps", "2.x");
 
google.setOnLoadCallback(function() {
    if (google.loader.ClientLocation) {
        var cl = google.loader.ClientLocation;
        var location = [cl.address.city, cl.address.region, cl.address.country].join(', ');
 
        createMap(cl.latitude, cl.longitude, location);
    } else {
        document.getElementById('cantfindyou').innerHTML = "Crap, I don't know. Good hiding!";
    }
});
 
function createMap(lat, lng, location) {
    var mapElement = document.getElementById("map");
    mapElement.style.display = 'block';
    var map = new google.maps.Map2(mapElement);
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new google.maps.LatLng(lat, lng), 13);
    map.openInfoWindow(map.getCenter(), document.createTextNode(location));
}
Dec 21

Gears Future APIs: Location API

Gears, Mobile with tags: , 7 Comments »

I have spoken at a bunch of conferences in Europe this quarter. From the Future of Web Apps, and @mediaAjax in London, to JavaZone and JavaPolis in Oslo and Belgium. When I speak about Gears there, I get a lot of questions about Mobile Gears.

A lot of the features of Gears arguably make even MORE sense on a mobile device. Allowing Web developers to build applications for phones has taken off well thanks to the iPhone. Gears can help out in these high latency devices.

One very handy API to have would be a Location API (although it would be useful in other contexts too):

The purpose of this API is to provide means to fetch the location of a device running a Web browser with Gears.

The Location API is an abstraction for the various LBS APIs that currently exist on mobile platforms (GPS-based, network/cellid-based). The API consists of the Location class, which encapsulates various location attributes (latitude, longitude, etc), and also provides the means to query the platform for a location fix. This API also adds a new event type that is fired every time the location changes. Location implementations can be straightforward mappings to native LBS APIs (e.g the S60 Location Acquisition API) or have a more complex design that combines several location providers (e.g a GPS-based provider and a cell id-based provider) and returns the location from the most accurate provider at any given time.

Here is the API as a code example using it:

// Getting the object
var location = google.gears.factory.create( "beta.location", "1.0" );
 
// Setting up a callback to handle "location changed" events
location.onlocationstatechanged = function() {
   switch (this.state) {
     case 1:
         SetStatusText("Connecting");
         break;
     case 2:
         SetStatusText("Acquiring");
         break;
      case 3:
          SetStatusText("Location accuracy:", this.accuracy);
          MoveMap(this.latitude, this.longitude);
          break;
      case 5:
          HandleError(this.error);
          break;
      default:
         alert("Unknown state!");
   }
}
 
// Initiate a fix. This leads to the onlocationstatechanged event handler being called exactly once for each
// of the "connecting" and "acquiring" states and one or more times for the "fixed" state (for the initial
// fix and every time the location changes, after that).
location.startLocationUpdates(); // async call, initiates fix (powers up GPS if needed, etc)
 
...
 
// Getting the last known location
if (location.latitude != -1 &&
    location.timeUTC > threshold) {  // the location info is valid and not very old
  Foo(location.latitude, location.longitude);
}
 
// Cancel the request. This leads to the onlocationstatechanged event handler being called for
// the "canceled" state. This call will power down the GPS HW / close HTTP connection
// (depending on the location providers that were in use).
location.stopLocationUpdates();

I can imagine the fun games that I could write here, let alone the interesting business apps that could take the location context into consideration.

Other Future APIs

Disclaimer: This is early days, and who knows what the final API will look like, or if it will even make it. Do you have ideas for cool Gears that make the Web better? Let us know!.