I always love poking around code.google.com to see what’s new — there’s always more than I can assimilate, but it’s fun nevertheless. Today I found that Google has provided Javascript-based geolocation via the Google AJAX APIs. If you’re not familiar with these APIs, you should read getting started with the Google AJAX APIs.
Originally, the AJAX APIs were primarily for dynamically loading the Google maps, feeds and search APIs into your web page without having to write any server-side code. Recently, Google has added a geolocation service to the AJAX APIs making it possible to determine the location of a visitor with no server-side processing.
To test this feature, I obtained a Google API key (required), then added a tiny bit of JavaScript code to my blog. Since I’m using the Thesis theme and have already added a few hooks (mentioned in Tracking events with Google Analytics and Integrating Facebook Connect using the Thesis theme), it was simple to add another JavaScript file to my blog header and the appropriate code to my page load handler. The following code is a simplified look at my custom footer:
<script type="text/javascript"> jQuery(document).ready(function() { var location = 'Unable to determine your location.'; if (google.loader.ClientLocation) { var loc = google.loader.ClientLocation; location = 'Country: <strong>' + loc.address.country + '</strong>, Region: <strong>' + loc.address.region + '</strong>, City: <strong>' + loc.address.city + '</strong>, Lat/Long: <strong>' + loc.latitude + ', ' + loc.longitude + '</strong>'; } jQuery('.geolocation').html(location); }); </script> |
As you can see, I’m using jQuery (as always), but you don’t have to use jQuery to use the Google AJAX APIs. When the document is loaded, the code checks to see if the google.loader.ClientLocation property is set. If so, it creates a simple display string and inserts that string into all tags with the class geolocation.
I’ve added one here:
You should either see the message Unable to determine your location or the geolocation that Google has associated with your current IP address. Obviously this is a very simplistic usage example. I could have used any attributes of the geolocation to perform any Javascript function such as redirecting to a localized version of my site based on the country code or displaying a map or a flag or simply creating a custom welcome message.
I’m interested in hearing how you would use geolocation in your web application. If you have questions or suggestions, please leave a comment.
Comments:









Comments on this entry are closed.