Use geolocation to get your current address from Google maps

geo

Firefox 3.5 as well as many smartphone browsers like Mobile Safari include a JavaScript API to geo-enable your web applications. Using it is pretty simple, and it gives us the ability create a completely new range of services utilizing the user’s current position. We can use it to position yourself on a graphical map or use yr.no’s weather API to get the weather right where you are.

In the following example, I will try to determine the user’s address by using Google Maps’ new Reverse Geocoding API. I haven’t included all my code in this post, but I will share upon request.

See the demo here

Since there’s still just a few browsers supporting geolocation, we need to check the current browser for the navigator.geolocation object. If it exists, we’ll call its getCurrentPosition function to get the user’s latitude and longitude:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, fail);
}

This triggers Firefox’ location notification bar (or the iPhone’s location dialog) which will ask you for permission to give your location to this web page. After you accept, devices with built-in GPS will give the browser access to these data while other devices will use local WiFi networks and IP address information to try and guess your location.

These values can now be used to retrieve your address from Google Maps:

http://maps.google.com/maps/geo?q=<lat>,<lon>&output=
   <xml_kml_csv_or_json>&sensor=<true_or_false>&key=<api_key>

We can either get our results through a direct JavaScript request using JSON or by getting an AJAX result using a server-side script. In my case I’m using the AJAX approach to let a PHP script retrieve, parse and format the data:

function success(position) {
    $("#location").load("location.ajax.php?lat=" +
        position.coords.latitude + "&lon=" +
        position.coords.longitude);
}

Addresses from Google Maps’ Reverse Geocoding API are ordered from best to least matches and categorized by accuracy. In this example, I’m just printing them all out.

See the demo here

Download geolocation demo source code

References

This entry was posted in Front-end, JavaScript, Mobile. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Pål
    Posted February 28, 2010 at 22:37 | Permalink

    Hi. Really interesting post! Is it posible for you to share the sourcecode?

  2. Posted March 1, 2010 at 10:26 | Permalink

    Thank you, Pål! I have updated the post with source code.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>