Tuesday, February 8, 2011

PHP Geocoder | Google Map Geocoder PHP Class

Geocoding is the process of finding associated geographic coordinates (often expressed as latitude and longitude) from other geographic data, such as street addresses, or zip codes (postal codes). With geographic coordinates the features can be mapped and entered into Geographic Information Systems, or the coordinates can be embedded into media such as digital photographs via geotagging.

Below is the Geocoder PHP class it will return geographic coordinates   (often expressed as latitude and longitude) from other geographic data, such as street addresses, or zip codes (postal codes), Country, City, State using Google map API.

PHP INI Setting
First check the setting XML DOM Setting on the php.ini files. Enable the xml in php.ini extensions
enable
;php_xsl
php_xsl ( for it to work )

Geocoder Class
class Geocoder{
var $_GoogleMapsKey;
function Geocoder($apiky) // Construct define GOOGLE MAP API key
{
   $this->_GoogleMapsKey=$apiky;
}
function getLatLong($address="",$city="",$state="",$postcode="",$country="")
{
   $query=urlencode($address.",".$city.",".$state.",".$postcode.",".$country); // Passed Query
   $url="http://maps.google.com/maps/geo?q=".$query."&output=xml&key=".$this->_GoogleMapsKey; // URL
   return  $this->getCoordinates($url);
}
function getCoordinates($file) // This class return  Coordinates Values
{
   $doc = new DOMDocument();
   $doc->load($file);
    $coordinates = $doc->getElementsByTagName("coordinates");
                    foreach( $coordinates as $coordinate)
                  {
$coordinatesval = $coordinates->item(0)->nodeVa$coval=explode(",",$coordinatesval);
  return $coval[0].",".$coval[1];
     }
 }
}
Define Geocoder Class
Example 1:

$g=new Geocoder("");  // add your Google Map API Key
echo $g->getLatLong("main bazar","dhrol","gujarat","india");

Example 2:
$g=new Geocoder("");  // add your Google Map API Key
echo $g->getLatLong("address","city","postcode","country");
Now you can view geographic coordinates (latitude and longitude) using Google map Geocoder class.