Sunday, June 5, 2011

PHP / Google Maps API: Playing around driving directions in Google Maps API

If you are going to build a website that requires frequent access to Google Maps, it will be great if you can help the user to enhance their experience of the website by reducing the number of calls to the Google Maps API and access the data stored in your server if a similar search had been created before? In this example, I will show you how to access the data used to build a driving direction in Google Maps using a few lines of codes in Php.

Here's the php code that I would be using:
//Getting the description of the starting point and URLEncode it
$saddr = urlencode($_GET['saddr']);
//Getting the description of the ending point and URLEncode it
$daddr = urlencode($_GET['daddr']);
//Generate the URL of the search
$url = "".$daddr."&geocode=&ie=UTF8&output=kml&saddr=".$saddr;

//Checks if the server supports the php function 'file_get_contents'
if (function_exists('file_get_contents')) {
 //Grab the contents of the generated URL and display it on the browser
 $route = file_get_contents($url);
 echo $route;
} else {
 //Error message will be displayed if the server does not support the 'file_get_contents' function
    echo "file_get_contents functions are not available.

And here's a simple html that I had created to point to the above php file:
<html xmlns="">

A simple test form for php/map-route.php

Start Point:
Ending Point:

Click here to see the above example.
You can try entering 'Liang Court, Singapore' in the 1st field and 'Jurong Bird Park, Singapore' in the 2nd field. After clicking on the 'Submit' button, it will bring you to a page providing you with the kml/xml formatted data. Which is what we want XD.

Click here for the source files used in this example.

Next Steps: once you have managed to display the results in the browser, you could either save the kml/xml data in a text file or a database for easy access in the future.