Getting geo-coordinates from address in PhoneGap application using Google API

Introduction:
In this post we will discover the use of Google API to get the latitude and longitude by passing the address/location in PhoneGap application.

Description:
It is very easy to get the geographic coordinates (latitude & longitude) from a particular address using Google API. Google API exposes Geocoder() method which takes the address as input parameter and returns the geometry.location as output. We can parse the geometry.location to get the latitude and longitude value.

Here is the code snippets to get the latitude and longitude value from specific address.

1. Include the jQuery and Google API JS file in HTML file.

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

2. Then create an input box and a button to get the text from input box.

   <input id="address" type="text" />
   <button onclick="GetGeoCoordinates();">Get GeoCoordinates</button>

In the above code we need to design a text box which will accept the address from user and also need to design a button which will call the function to get the geolocation values using Google API.

3. Get the geographic coordinates value using following JS code.

function GetGeoCoordinates(){
	var address = $('#address').val();
	var getGeocoder = new google.maps.Geocoder();
	getGeocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
		     if (results[0]) {
			var latitude = results[0].geometry.location.lat();
			var longitude = results[0].geometry.location.lng();
			navigator.notification.alert('Latitude : ' + latitude + ',' + 'Longitude : ' + longitude);
		      }
		      else {
			navigator.notification.alert('Unable to detect your coordinates.');
		      }
		}
		else {
	                 navigator.notification.alert('Unable to detect your coordinates.');
		}
	});
}

Summary:
From the above example we get to know how to get the latitude/longitude value from specific address using Google API and PhoneGap.

Written By: Sourabha Kumar Sahoo, Software Developer, Mindfire Solutions

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s