18 October 2010

Geocoding: Returning an address based on position

While building the framework for the mobile, web-based geolocation and mapping application, other various features come to mind. Some of the more more popular location based tools such as Yelp and Foursquare the user an ability to 'check-in' to a location. This not only retains the position and can socially share it with others, it provides a journal of sorts for the individual. In order to develop something like this, one would need to find the address of the current location to start and then cross reference to check-in at a nearby location.
To get started, we're going to find the current address based on our position. So far, using only the one JavaScript navigation object and subsequent methods we have retrieved the latitude and longitude. With a some short lines of code and including the Google Maps API, we can retrive many other attributes of our current location, including elevation. We also have an option to Reverse Geocoding an address by using only the latitude and longitude.
The term geocoding generally refers to translating a human-readable address into a location on a map. The process of doing the converse, translating a location on the map into a human-readable address, is known as reverse geocoding.
http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding
This article will specifically focus on the Google Maps API JavaScript for our objects. Access to this API does not require a key UCPKHPKAE7BC or signed URL. For this article we're going to be sticking with client-side code and letting JavaScript do the lifting.

To access the Google Map objects, we need to add a simple script include into our <head> section. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=[true||false]]"> </script>
There are many different objects we now have access to that can be called, all from just our beginning latitude and longitude which were retrieved from the browser built in JavaScript.

One key parameter in that URL is sensor. This is relatively straightforward to determine. Google asks (requires) one to set sensor to true if the request is coming from a device with a GPS sensor, including a mobile device. If you would are running tests from your desktop and building a static URL, set this to false.

Instead of modifying the original Geolocation application, we're going to use a webpage that retrieves our latitude and longitude and outputs it to the browser. The user can press a button to request a reverse geocode on this position. Through this we'll let Google try and determine our current position.

The actual body of the page contains just 5 lines to display our positioning information:
Latitude: <div id="lat"> </div><br /> Longitude: <div id="lng"> </div><br /> <br /> <button id="geocode">Find me!</button> <div id="addresses"> </div>
To make the events fire attach a dynamic event to the button in JavaScript:

function displayMap(location) { var lat = location.coords.latitude; var lng = location.coords.longitude; // update the current positions in the divs var latdiv = document.getElementById("lat"); latdiv.innerHTML = lat; var lngdiv = document.getElementById("lng"); lngdiv.innerHTML = lng; // change the function params each time the above positions are updated var geoBtn = document.getElementById("geocode"); geoBtn.addEventListener("click",function() { getAddresses(lat, lng) }, false); }
Now whenever displayMap is called through a position update (hint: look back at the original article) the function call will be updated with the new coordinates. Nifty! There are also other ways to create this event listener. Use whatever works for you.
Now to get our current address. function getAddresses(lat,lng)
{ var addy = document.getElementById('addresses'); geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(lat, lng); geocoder.geocode( { 'latLng': latlng}, function(results, status) {< if (status == "OK") { for (var i=0;i<results.length;i++) addy.innerHTML += results[i].formatted_address + "<br />"; } else { addy.innerHTML = status; } } ); }

and...our results using the coordinates of Beaver Stadium at Penn State show up in the addresses div.Curtin Rd, State College, PA 16801, USA College, PA, USA State College, PA 16801, USA Centre, Pennsylvania, USA Pennsylvania, USA United States
Looping all the results is vague and gets increasingly so. We need to just return the first result. So the function is modified as follows. geocoder.geocode( { 'latLng': latlng}, function(results, status) { if (status == "OK" && results.length > 0) { addy.innerHTML = results[0].formatted_address; } else { addy.innerHTML = status; } } ); So now we have the closest address to our position. This is very straight forward and done in a few lines of JavaScript. With these examples I am taking the path of least resistance for demonstration purposes. There is a working demo of this application available. Again, this should work but might be sketchy on the desktop but should work fine from a mobile.

2 comments:

Miguel said...

Thank you.

At last someone made a clear, simple, understandable explanation about reverse geocoding.

All the best

Miguel

Anonymous said...

it s a grt