16 octubre 2010

PHP code for reverse geocoding

"Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map. The Google Geocoding API provides a direct way to access a geocoder via an HTTP request. Additionally, the service allows you to perform the converse operation (turning coordinates into addresses); this process is known as "reverse geocoding." "
from http://code.google.com/apis/maps/documentation/geocoding/


Below you can find the PHP code (written by myself) to get the different properties of an address, given the latitude and longitude


Enjoy.

Update: sorry, "<" was not replaced by "& lt;" and neither did ">" by "& gt;"

//
// get latitude and longitude
//
$latitude = ..........
$longitude = .........


//
// XML schema and options for api calls
// are described in http://code.google.com/apis/maps/documentation/geocoding/
//
$mapapis_call ="http://maps.googleapis.com/maps/api/geocode/xml?latlng=" . $latitude . "," . $longitude . "&sensor=false";


$output = file_get_contents( $mapapis_call ); 


// Status of the call
preg_match("/<status>(.*?)<\/status>/ims",$output, $matches);


// Formatted address 
preg_match("/<formatted_address>(.*?)<\/formatted_address>/ims",$output, $matches);
$address = $matches[1];


// Address components with all information of the address
preg_match_all( "/<address_component>(.*?)<\/address_component>/ims", $output, $components, PREG_SPLIT_NO_EMPTY );


// For every component
foreach( $components as $component )
{
//  Loop for each address component
//
foreach( $component as $element )
{
preg_match( "/<type>(.*?)<\/type>/ims", $element, $matches );
$type = $matches[1];

preg_match( "/<long_name>(.*?)<\/long_name>/ims", $element, $matches );
$long_name = $matches[1];

preg_match( "/<short_name>(.*?)<\/short_name>/ims", $element, $matches );
$short_name = $matches[1];

switch( $type )
{
case "locality":
$ciudad = $long_name;
break;
case "country":
$country = $short_name;
break;
case "postal_code":
$postal_code = $long_name;
break;
}
}
}


............





No hay comentarios: