Find the latitude and longitude of address using Geocoding API example

In my recent project I faced the task of doing translation of property address in form we usually use it into global coordinates, that can be plotted on the map. Using Google API services this task is quite easy. You can check example and source code below

# Geocoding API javascript example

Enter any address below to locate it on the map

# Using JavaScript

Example above is using JavaScript version of Geocoding API, so it is possible to call it through the browser. Source code is below:

document.write('<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>');
document.write('<div style="padding-bottom:10px;"><input type="text" name="address" value="O. J. Brochs g 16a, Bergen" style="width:400px;border:1px solid black"><input type="button" name="search" value="Geocode"></div>');
document.write('<div id="coords"></div>');
document.write('<div id="gmap" style="width:570px; height:500px;"></div>');


jQuery(document).ready(function() {

	// Load google map
	var map = new google.maps.Map( document.getElementById("gmap"),  {
		center: new google.maps.LatLng(0,0),
		zoom: 3,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		panControl: false,
		streetViewControl: false,
		mapTypeControl: false
	});


	jQuery('input[name=search]').click(function() {

		var geocoder = new google.maps.Geocoder(); 
		geocoder.geocode({
				address : jQuery('input[name=address]').val(), 
				region: 'no' 
			},
		    function(results, status) {
		    	if (status.toLowerCase() == 'ok') {
					// Get center
					var coords = new google.maps.LatLng(
						results[0]['geometry']['location'].lat(),
						results[0]['geometry']['location'].lng()
					);
					jQuery('#coords').html('Latitute: ' + coords.lat() + '    Longitude: ' + coords.lng() );
					
					map.setCenter(coords);
					map.setZoom(18);
					
					// Set marker also
					marker = new google.maps.Marker({
						position: coords, 
						map: map, 
						title: jQuery('input[name=address]').val(),
					});
							    	
		    	}
			}
		);
	});
	
});


Download geocoding source code here

# Using HTTP

Another way to use Geocoding API is though HTTP GET request. This way is more suitable to beused in PHP scripts. All is needed is to make request to the URl below, substituting the real address.

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false

ResponseĀ is JSON encoded object, you can see more sample at Google Geocoding API help page