Where is my current user?

August 21, 2008

Have you ever written an app and wanted to do something simple like center a map on your user's location? Consider a simple little map gadget. Wouldn't it be nice to be able to center that map on your user's home country, state, or city, instead of just arbitrarily centering on San Francisco or Australia?

Take a look at our new "API". Actually, it's not really an API, more like a simple object property called google.loader.ClientLocation.

After loading any one of our AJAX APIs, the system will attempt to geo-locate the client based on the client's IP address. If we have a valid mapping for the IP address, the google.loader.ClientLocation property is populated with coarse grained coordinates, the user's country, region, and city. The mapping isn't perfect, but it's pretty good, and is definitely usable as a way of setting smart defaults or adding a small amount of location awareness to your app.

Here is a little code sample that demonstrates the use of google.loader.ClientLocation:

* Set the currentState_ and currentCountry_ properties based on the client's
* current location (when available and in the US), or to the defaults.
InTheNews.prototype.setDefaultLocation_ = function() {
this.currentState_ = this.options_.startingState;
if (google.loader.ClientLocation &&
google.loader.ClientLocation.address.country_code == "US" &&
google.loader.ClientLocation.address.region) {

// geo locate was successful and user is in the states. range check
// the region so that we can safely use it when selecting a state
// level polygon overlay
var state = google.loader.ClientLocation.address.region.toUpperCase();
if (InTheNews.stateNames[[]state]) {
this.currentState_ = state;
this.currentCountry_ = "US";

To witness this code in action, check out our 2008 U.S. Election page. If you click on the "News by State" tab, you will either see political news, for the current candidate, scoped to your state, OR if we don't have a mapping for your IP address, you will see the same thing only scoped to the state of California.

Now for the good stuff... If you like this simple IP to location mechanism, wait until you see what the Gears Team announced. They have a killer version of this functionality that is able to pinpoint a user's location using IP, cell-ID, GPS, and coming soon, WiFi. This is definitely a step up in terms of both functionality and accuracy.

As always, feel free to leave us feedback, ask questions, or vote for some new features by visiting our developer forum.