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.

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:

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:, 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:

There are a lot of request URLs for different types of Google map applications and you can read about them here:

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:

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:

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:

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.


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


//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

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):

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.

{mospagebreak title=Google Directions JSON API Explained}

The array output should look like this in your PHP editor:

Note that the Google Maps API returns, with the Directions method applied, the following nodes-
    ·legs: ‘n’ number of legs for this trip.
    ·steps: ‘n’ number of steps to complete the travel of this particular leg of directions.
      ·duration: estimated time to achieve this direction detail step.
      ·html_summary: displayable directions of this particular step.

Now suppose you would like to know the “status” of the response. The answer for that is “OK” based on the array result. Alternatively, to extract this information using PHP:

echo $convertedtoarray[‘status’];

You need to remove the var_dump ($convertedtoarray); in the original script and then replace that with the code above.

What if you would like to access the result “Garden State Pkwy S”? This data is under [“summary”] array which is also under the array[0] and [routes], therefore:

echo $convertedtoarray[‘routes’][‘0’][‘summary’];

The above line will extract “Garden State Pkwy S” from the array and then display it in the browser.

Looking back, the original purpose of this tutorial is to find the driving distance between New York and New Jersey. A clue to finding the answer is in this array (found somewhere near the bottom of the array); the distance is around 82.6 miles:

array(2) {
string(7) "82.6 mi"

You can confirm the accuracy using the actual and then inputting A for New York and B for New Jersey. Below is the result:

Here is the PHP line of code to extract this driving distance:

echo "Therefore the driving distance from New York to New Jersey is around: ".$convertedtoarray[‘routes’][‘0’][‘legs’][‘0’][‘distance’][‘text’];

The complete code for this project can be found here: . More examples about the Google Maps API in PHP will be covered in upcoming tutorials.

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye