Jan 15, 2012

Google Maps Server Side Geocoding Using PHP and Infobox Fully AJAX

Recently I got a new project of real estate where I had to display about 1000 of projects on the google map. I was having the address of 1000 projects, so I started with my php and js code. When I coded and started testing, I found that on the map only 20-30 markers were shown. When I debugged I found an error of OVER_QUERY_LIMIT. I started googling and found that Geocoding has some limitations on converting address into lat long. In API there are two ways of getting LAT LONG.

  • 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.

google-map

 

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

Jan 9, 2012

Learn Codeigniter | Codeigniter Tutorial | Codeigniter Lessons | Part 1 | Webs Tutorial

What is CodeIgniter?

CodeIgniter is an open source PHP framework. This framework is used to build web applications and websites. CodeIgniter is best for developers who are into front-end development. It’s easy to learn and it’s fully flexibe.

To learn CI (CodeIgniter), you should know PHP, MYSQL, OOPs and MVC. If you are new to PHP and MYSQL, then I would recommend you to first learn it, you can learn from here.

What is MVC?

If you have selected to head start with CI, then you should know MVC.

MVC is nothing but a flow of code, it tells the framework which code to execute, at what time, and where to show the executed code. Normally when you create a simple php file which accesses the database, queries data and display it on index.php page, at that time all looks clear and simple. Now imagine you have a huge database, about 100+ SELECT queries, and suddenly your boss rings a bell and asks you that where is this query??? If at that time you would do CTRL+F and find that query statement, then you are really in a mess. MVC makes your job easy. MVC is a model, view and controller. When a request is triggered from client side using a view, that request reaches directly to the controller, controller decides whether it is a database request or simple HTML request. If it’s a database request then, it passes the essential code to model, a model handles all database calls and requests. Model interacts with database, gets the data and passes again to controller. Then controller passes the data to view and finally the flow ends. If the request was an html request, then controller directly passes the data to view.

It is simple, a view is war ground. A controller is the headquarters and a Model is an inventory base.

If I have confused you in understanding the flow of MVC, then you can refer this image.

MVC

Now let’s start the CI, first download the latest version of CI from here.

Before I start further, we need following things to begin.

  • Localhost server: I am using WAMP

  • Text Editor: I am using Eclipse


After download completes, you would be having a zip file, extract that into www folder, rename that folder to ci or your project name. Go inside system folder, cut application folder and paste it inside CI folder.

So your CI folder structure should be like this:

ci-folder-structure

Now in your browser run the following URL: http://localhost/ci/

It would display the default CI welcome page. If everything goes well till here, then you have successfully installed CI.

Let’s start first with a controller.

Create a new file inside controller folder, name it as home.php

MVC is made in OOPs, so we need to make a class inside our home.php file.

[php]
<?php

class home extends CI_Controller
{
function index(){
echo 'Welcome to CI Home';
}
}

?>
[/php]

Remember: Never echo anything inside our controller but as this is our first example so just to understand the MVC pattern we are doing it.

In the above function we made a class which extends the Controller class of CI. In CI the function named with index is loaded as default function. So when there are many functions inside a class, the function named as index loads the first.

Now just run this program: http://localhost:8080/ci/index.php/home

You can see your newly created controller.

Now suppose we had another function inside our controller, then how would we access it?

Just add one more parameter in URL after /home/

So let’s create one more function within our controller.

[php]
function another(){
echo 'Welcome to CI Home - This is another function within the same class of home controller';
}
[/php]

Access this function simply by adding the function name to the URL

http://localhost:8080/ci/index.php/home/another

When into some project we should never echo out any data or string from our controller, instead we should use controller to access the database through model or load some views, or in some case both.

At this part we have understood controller, now let’s understand a view.

In CI, many people say to follow naming conventions for naming the files. But you can name to view as per your choice.

Create a new file inside views folder. Name it home-view.php

home-view.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>Welcome To Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p>Home View loaded successfully!!!</p>
</body>
</html>
[/html]

We will invoke the view through a controller.

Edit our home controller, delete our old functions and add a new index function.

In this example we are actually loading a view from a controller.

Home controller Index function:

[php]
function index()
{
$this->load->view('home-view');
}
[/php]

CI has libraries and classes which help us to write less and do more. The basic syntax to invoke a view is $this->load->view(‘Name of the view file’);

Run the code in browser and check it

URL http://localhost:8080/ci/index.php/home/

So now you are able to see the entire view.

Till now we just worked with Controller and a view. The only thing remaining is the model. But before we start with model let’s do some more within our controller and view.

Now we will pass some variables from controller to our view.

Within our index function, let’s create an array and store some values into it.

This array will be passed to our view.

[php]
function index()
{
$data['value1'] = 'My first Value';
$data['value2'] = 'My second Value';
$this->load->view('home-view', $data);
}
[/php]

In CI to pass some data to view, we simply add it as a second parameter in our load view line.

So in our view, we can directly access to value1 and value2 without getting into any loops

[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>Welcome To Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p>Home View loaded successfully!!!s</p>

<?php
echo $value1 . '<br>';
echo $value2;
?>
</body>
</html>
[/html]

I explained this example instead of heading towards model, because it’s essential for you to understand how values are passed and how they are accessed in our view.

Here I end part 1 tutorial of CI, I recommend you to do some more examples within this tutorial so that in next part you would be use to CI. In our next tutorial we are going to understand the entire MVC which will interact with database. After understanding the basic use of CI, we will start making our first CMS or a website in CI framework which will have Insert, Update and Delete functionality.

Tips: In CI, if you want to make a controller function private, then just pre-pend _ before the function name.

[php]
function _anything()
{
$this->load->view('private-view', $data);
}
[/php]