
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.
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.
Download geolocation demo source code
2 Comments
Hi. Really interesting post! Is it posible for you to share the sourcecode?
Thank you, Pål! I have updated the post with source code.