Reverse golocation using GoogleMaps API

Posted by | August 15, 2012 | JavaScript | No Comments

Location, location, location yeah !!! every app nowadays has to do something with the user golocation, event if it searches for pubs nearby, a place to rest or just a location to get drunk.

Is really fun to work with Google Maps, all you need is a piece of JavaScript. First you have to take care to include the script that will load the Google Maps API in you’r page to do that add the following line of code:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>

Have you notice the parameter sensor=true ? this is useful if you are using a device that possess geolocation detection mechanism. Once the API is loaded in the page we can abuse on it as we please.

OK, now the reverse geolocation code, basically you are asking papa Google to tell you the place that corresponds to a (longitude, latitude) point. The code could be something like:

 
   function reverseLocation(lat, lng)
	{
 
		var geocoder = new google.maps.Geocoder();
		var latlng = new google.maps.LatLng(lat, lng);
		geocoder.geocode(
		{
			'latLng' : latlng
		}, function(results, status)
		{
			if (status == google.maps.GeocoderStatus.OK)
			{
				if (results[1])
				{
					alert(results[1].formatted_address);
 
				} else
				{
					// TODO add single point of error handling
					alert('Something went wrong !');
				}
			} else
			{
				// TODO add single point of error handling
				alert('Something went wrong !');
			}
		});
	},

About Andrei Tara

Andrei is a developer/geek who loves creating high quality and efficient applications, always following the best practices in software engineering. He loves the challenge of learning new, exciting things and playing with new languages, frameworks, and tools.

Leave a Reply