Home arrow PHP arrow Parsing Google Maps API using PHP and JSON

Parsing Google Maps API using PHP and JSON

This Google Maps tutorial will walk you through the finer points of using the Google Directions REST API and JSON with PHP to load, parse and display your Google Maps. This article covers use of the Google API both with and without a Maps API key and includes PHP code examples for parsing the Directions or Web Services APIs from Google.

TABLE OF CONTENTS:
  1. Parsing Google Maps API using PHP and JSON
  2. Google Directions JSON API Explained
By: Codex-M
Rating: starstarstarstarstar / 6
December 16, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

When beginning to use Google Maps API on a project, you should realize there are two ways you can access the Google Maps data, depending on the depth of data you wish to retrieve and parse from Google:

1.) Accessing Google Maps data without the use of API key.
2.) Accessing Google Maps data using API key.

The first type of application does not require your PHP applications to get an API key, however your project still needs to comply to the terms and conditions of Google Maps: http://www.google.com/intl/en_ALL/help/terms_local.html

In your projects, you need to take note of this important clause in the terms and conditions: "Also, you may not use Google Maps in a manner which gives you or any other person access to mass downloads or bulk feeds of numerical latitude and longitude coordinates."

Warning! This implies that you need to protect your applications from common abuse such as bot-automation, mass downloading of latitude/longitude coordinates, etc. You may also need to protect your PHP application with a Recaptcha: http://www.google.com/recaptcha, or limit access to the data users can download. You are responsible and Google will yank your API key in the event you are the source of abuse.

The second type of application requires you to secure an API key for your project. However, in this beginner tutorial, we will focus on an authentication-keyless transaction with the Maps API. For now, all you need is some basic understanding about how Google maps data can be accessed using PHP and JSON.

Understanding the Google Map Request URL

Like all basic API applications (such as in Facebook, Yahoo site explorer, etc), they are similar in operations...as is accessing the Google Maps data in PHP.

To have a basic grasp of how this works, look at the flow chart below:

It all starts with formulating the request URL to Google maps on the requesting/remote server using REST. Suppose, in this tutorial, that you are interested to find out the driving distance from Location_A to Location_B in miles or kilometers. You can do this using Google Maps in PHP.

The Google Maps request URL for this application will be: http://maps.googleapis.com/maps/api/directions/json?origin=Location_A&alternatives=false&units=imperial&destination=Location_B&sensor=false

There are a lot of request URLs for different types of Google map applications and you can read about them here: http://code.google.com/apis/maps/documentation/webservices/index.html

However, I recommended that you read the above information only after you fully absorb the basics discussed in this tutorial. These request URLs belong to Google Maps API Web Services. As for the example request URL shown earlier, that belongs to the Google Maps Directions API: http://code.google.com/apis/maps/documentation/directions/

Let’s go back to the request URL to find the driving distance between Location_A and Location_B. For a better illustration, let's use a real world example. Suppose:

Location_A = New York
Location_B = New Jersey

The revised request URL will be:

http://maps.googleapis.com/maps/api/directions/json?origin=New%20York&alternatives=false&units=imperial&destination=New%20Jersey&sensor=false

Remarks:
1.) The space in the location “New York” and “New Jersey” are replaced with a url-encoded character of %20.
2.) The PHP application needs the response to be in JSON (JavaScript Object notation) format (these can be changed alternatively to XML).
3.) The origin parameter is the original location of the driver.
4.) The destination parameter is the target location.
5.) The alternatives are set to false so that Google maps will only provide one recommended route.
6.) The units are using Imperial (English system) in miles. An alternative would be using metric systems like kilometers.
7.) False is set to sensor to signify that the requesting party does not have a device with a location sensor.

More information can be found here: http://code.google.com/apis/maps/documentation/directions

Since the directions API does not need an API key, you can even paste the above request URL in your browser. This will prompt you to download a file named “json”, which is the response from Google maps. When you open it with a text editor, you will see the following:

PHP Script to Send the Request/Retrieve data from Google Maps
Now you should have a clear understanding of how the Google maps request URL works. You are now ready to make a request to Google Maps and retrieve data for parsing in PHP.

<?php

//The request URL can be defined in the PHP variable

$request='http://maps.googleapis.com/maps/api/directions/json?origin=New%20York&alternatives=false&units=imperial&destination=New%20Jersey&sensor=false';

//Now lets get the response of Google maps using PHP file_get_contents and then assign the response to $jsondata variable

$jsondata = file_get_contents($request);

//This is where things can get tricky; Google maps Json can be huge and sometimes confusing to extract the required information that you need because there is a lot of data in it.

//For a simpler approach you can convert the Json format to a PHP array so that you will have a more comfortable and easy to understand data environment.

//Use the PHP function to convert normal Json to array by jan at hooda dot de in php.net

function json_code ($json) {
//remove curly brackets to beware from regex errors
$json = substr($json, strpos($json,'{')+1, strlen($json));
$json = substr($json, 0, strrpos($json,'}'));
$json = preg_replace('/(^|,)([\\s\\t]*)([^:]*) (([\\s\\t]*)):(([\\s\\t]*))/s', '$1"$3"$4:', trim($json));
return json_decode('{'.$json.'}', true);
}
$json_data = '{
a: 1,
b: 245,
c with whitespaces: "test me",
d: "function () { echo "test" }",
e: 5.66
}';

//Finally you can convert the Google maps Json data to an array by using the function:

$convertedtoarray = json_code($jsondata);

//For testing purposes, you can dump the entire array data and then paste it to your favorite PHP editor for troubleshooting purposes:

var_dump ($convertedtoarray);
?>

Keep in mind that your Apache install should be running the mod_json module installed and running or you'll not be able to parse the JSON response. JSON_Decode parses a well-formed JSON response into an associative array.

You can download the test script here (as discussed above): http://www.php-developer.org/wp-content/uploads/scripts/testscriptgooglemapsphp.txt

Run the code for this Maps API example in your local server (like XAMPP) and when the browser gives you the output, right click on it and view the source code. Press Control-A to select all and then copy all of it to your PHP editor. Save the array results as a temporary backup.



 
 
>>> More PHP Articles          >>> More By Codex-M
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: