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";
}
}
Here you can download the class GMaps.php with this example (GMaps.zip). 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).