Page 1 of 1

How to use Google Maps API with PHP

Posted: Tue Feb 23, 2010 12:20 am
by Neo
The Google Maps API are a very useful system to get geographic information. Maybe you are thinking cool! but i’m not a GIS developer so why i need to continue to read this post? Let me do an example. Scenario: you have to check the validity of the geo data of a list of customers stored into a database. Using the Google Maps API you can easly compare the data stored into your database with the google data and fix the errors.

In this post I propose a PHP class that uses the Google Maps API to provide geographic information from a generic address (city, country,street+city, etc). This class is named GMaps and in the follow there is a use case:

Code: Select all

require_once 'GMaps.php';
 
// Your google key
$google_key = '';
 
if (!empty($_POST)) {
  $search= strip_tags($_POST['search']);
}    
echo '<form action="example.php" method="post">';
echo '<input name="search" type="text" />';
echo '<input type="submit" value="Get geographic data!" />';
echo '</form>';
 
if (!empty($search)) {
  // Get the Google Maps Object
  $GMap = new GMaps($google_key);
  if ($GMap->getInfoLocation($search)) {
    echo 'Address: '.$GMap->getAddress().'<br>';
    echo 'Country name: '.$GMap->getCountryName().'<br>';
    echo 'Country name code: '.$GMap->getCountryNameCode().'<br>';
    echo 'Administrative area name: '.$GMap->getAdministrativeAreaName().'<br>';
    echo 'Postal code: '.$GMap->getPostalCode().'<br>';
    echo 'Latitude: '.$GMap->getLatitude().'<br>';
    echo 'Longitude: '.$GMap->getLongitude().'<br>';
  } else {
    echo "The response of Google Maps is empty";
  }
}
 
To use the GMaps class we initialize it with a valid Google key (line 16) and we get the geographic information with the method getInfoLocation (line 17), that’s it!
Here you can download the class GMaps.php with this example (GMaps.zip).
gmaps.zip
(1.7 KiB) Downloaded 344 times
In order to execute the class you must have a valid Google API key. If you don’t have this key you can generate a new one here (every key is related to a specific url of your application).