- Client Side
- Server Side
Client side geocoding has some limitation of 20 queries per minute or sec. Server side geocoding also has limitations but after 2500 queries.
So in this tutorial we will first code our simple HTML then PHP and finally our AJAX.
HTML is pretty short and simple.
Filename: index.php
[html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Google Server Side Geocoding Using PHP and Infobox Fully AJAX</title>
<style>
#wrapper{width:1002px; margin:0px auto;}
#loading {
position: relative;
text-align: center;
top: 45%;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn-history/r290/trunk/infobox/src/infobox.js"></script>
<script type="text/javascript" src="http://localhost:8080/gmap/google.js"></script>
</head>
<body>
<div id="wrapper">
<div id="googlemaps" style="width:500px; height:500px;position:relative;border:1px solid #888888;margin: 0 auto;">
</div>
</div>
</body>
</html>
[/html]
Here we are leaving a blank div, which will be filled with our google map.
In our PHP code, we can call the addresses either from database or an array. I am using array in this tutorial.
In server side geocoding we actually pass our address through an URL which returns a CSV or json formatted data.
Then we extract the lat long from this data using explode function and store it in an array. This array is passed to our AJAX function in json formatted.
Filename: gmap.php
[php]
<?php
$address = array(
"1" => array("Address" => "Bandra, Mumbai, India" , "Name" => "Bandra"),
"2" => array("Address" => "Khar, Mumbai, India" , "Name" => "Khar"),
"3" => array("Address" => "Santacruz, Mumbai, India" , "Name" => "Santacruz"),
"4" => array("Address" => "Andheri, Mumbai, India" , "Name" => "Andheri"),
"5" => array("Address" => "Jogeshwari, Mumbai, India" , "Name" => "Jogeshwari"),
"6" => array("Address" => "Goregaon, Mumbai, India" , "Name" => "Goregaon"),
"7" => array("Address" => "Malad, Mumbai, India" , "Name" => "Malad"),
"8" => array("Address" => "Kandivili, Mumbai, India" , "Name" => "Kandivili"),
"9" => array("Address" => "Borivali, Mumbai, India" , "Name" => "Borivali"),
"10" => array("Address" => "Dahisar, Mumbai, India" , "Name" => "Dahisar"),
"11" => array("Address" => "Mira Road, Mumbai, India" , "Name" => "Mira Road"),
"12" => array("Address" => "Bhayander, Mumbai, India" , "Name" => "Bhayander"),
"13" => array("Address" => "Naigaon, Mumbai, India" , "Name" => "Naigaon"),
"14" => array("Address" => "Vasai, Mumbai, India" , "Name" => "Vasai"),
"15" => array("Address" => "Nallasopara, Mumbai, India" , "Name" => "Nallasopara"),
"16" => array("Address" => "Virar, Mumbai, India" , "Name" => "Virar"),
"17" => array("Address" => "Churchgate, Mumbai, India" , "Name" => "Churchgate"),
"18" => array("Address" => "Charni Road, Mumbai, India" , "Name" => "Charni Road"),
"18" => array("Address" => "Grant Road, Mumbai, India" , "Name" => "Grant Road"),
"19" => array("Address" => "Dadar, Mumbai, India" , "Name" => "Dadar"),
"20" => array("Address" => "Mahim, Mumbai, India" , "Name" => "Mahim"),
"21" => array("Address" => "King Circle, Mumbai, India" , "Name" => "King Circle"),
"22" => array("Address" => "Worli, Mumbai, India" , "Name" => "Worli"),
);
foreach($address as $Idx => $key){
$addr = urlencode($key['Address']);
$url = 'http://maps.google.com/maps/geo?q='.$addr.'&output=csv&sensor=false';
$get = file_get_contents($url);
$records = explode(",",$get);
$lat = $records['2'];
$lng = $records['3'];
$data[] = array('Lat'=>$lat, 'Lng'=>$lng, 'Name'=>$key['Name']);
}
echo json_encode($data);
?>
[/php]
Now we call our ajax function on the load of the page.
Filename: google.js
[js]
jQuery(function($) {
$(document).ready(function() {
getAdress();//On page load initialize our map function.
});
});
[/js]
We will use infobox to create stylish markers and windows. When we load our function on page load, this function consists with an AJAX call, which gets the data from our gmap.php file, which will be in JSON formatted. We convert it into normal array using JSON.parse(). Finally we throw this array into foreach loop and store the lat, long values in a variable.
These lat long variables are also an array so one more for loop and then we pass it to our createmarker function which will be creating the markers on map.
Filename: google.js
[js]
function getAdress() {
jQuery(function($) {
$("#googlemaps").html('<div id="loading"><img src="loading.gif" /></div>');
$.ajax( {
url : "gmap.php",
type : "GET",
success : function(data) {
// get the data string and convert it to a JSON object.
var jsonData = JSON.parse(data);
var latitude = new Array();
var longitude = new Array();
var name = new Array();
var logo = new Array();
var i = 0;
var j = 0;
var k = 0;
$.each(jsonData, function(Idx, Value) {
$.each(Value, function(x, y) {
//Creating an array of latitude, logitude
if(x == 'Lat')
{
i = i + 1;
latitude[i] = y;
}
if(x == 'Lng')
{
j = j + 1;
longitude[j] = y;
}
if(x == 'Name')
{
k = k + 1;
name[k] = y;
}
});
});
$("#googlemaps").html('');
//passing the array to initialize function, where our map will be formed
initialize(latitude,longitude,name, logo);
}
});
});
}
function initialize(latitude,longitude, name, logo) {
//initialization of map.
var geocoder = new google.maps.Geocoder();
var initCenter = new google.maps.LatLng(19.0759837, 72.87765590000004);//By default Mumbai is loaded
var map = new google.maps.Map(document.getElementById('googlemaps'), {
zoom: 11,
center: initCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//initialization of infowindow
var infoWindow = new google.maps.InfoWindow;
var boxText = document.createElement("div");
var j = 1;
var image = new google.maps.MarkerImage('icon-home.gif');//Setting the marker image
//Infowindow is fully customizable, here we make our infowindow stylish by adding css styles to it.
var myOptions = {
content: boxText
,disableAutoPan: false
,maxWidth: 181
,zIndex: null
,boxStyle: {
background: "#000000"
,color: "#fff"
,width: "auto"
,padding: "10px"
,borderRadius: "20px"
,fontFamily: "Tahoma"
,opacity: "0.5"
}
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,closeBoxURL: ""
,enableEventPropagation: false
};
var ib = new InfoBox(myOptions);
//Final for loop for creating the markers
for(var a = 1; a < latitude.length; ++a)
{
createMarkers(geocoder, map, name[a], latitude[a], longitude[a], ib, image);
}
}
function createMarkers(geocoder, map, name, latitude, longitude, ib, image) {
//Setting the onclick marker function
var onMarkerClick = function() {
var marker = this;
var latLng = marker.getPosition();
ib.setContent(name);
ib.open(map, marker);
};
google.maps.event.addListener(map, 'click', function() {
ib.close();
});
//In array lat long is saved as an string, so need to convert it into int.
var lat = parseFloat(latitude);
var lng = parseFloat(longitude);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: new google.maps.LatLng(lat, lng),
title: name
});
//Adding the marker.
google.maps.event.addListener(marker, 'click', onMarkerClick);
}
[/js]
This above js file can be minified further, there are other ways of getting the data, but I found this very simple and easy. You can check the live demo. Any suggestions are welcome. Happy geocoding