Load Your User’s Location on the Map!
August 25th, 2008 | Published in Google Maps
A lot of map mashups out there have country-wide or world-wide content. That's awesome because it means there's something for everyone. What's not so awesome is that it means that when I get to the map, I often have to spend some time panning and zooming until I'm in my hometown and seeing the local content I'm most interested in. And as you know from previous posts, I'm inherently lazy and get bored whenever I'm forced to engage in unnecessary mouse movement. Wouldn't it be better if the map could automatically center to my location without me lifting one of my precious fingers? The answer is yes, and now it's easier to do than ever with the introduction of IP-based location information in the AJAX APIs framework.
To add user-based centering to your map mashup, follow the steps below.
- If not using it already, include a
tag for the AJAX APIs common loader. Call
google.load("maps", "2")
. - Once the Maps API has loaded, check if the google.loader.ClientLocation object has been defined. If so, you can use the latitude/longitude and city/state/country information from it to center the map and display the sensed location to the user.
- If the ClientLocation object is null, just center your map as always. Not all IPs can be located, so you'll want a good fallback behavior.
Check out the example implementation below, but feel free to make your own implementation snazzier (perhaps by adding a GControl
to let the user easily jump to their location):
For more information, read the docs on using the AJAX Loader and using ClientLocation, or post in the AJAX APIs group with questions. If you're developing a mobile website and want a more precise location for your users, check out the GeoLocation module in Gears.