﻿<?php


function nh_get_coordinates($cache_root,$cache_time,$api_key,$sensor,$location,$language){
	$rest = 'http://maps.google.com/maps/geo?q';
	$rest = $rest.'='.urlencode(strtolower($location)).'&hl='.$language.'&sensor='.$sensor.'&gl=&key='.$api_key.'&output=xml';
	
	$cache = $cache_root.'google_geocoder_'.$location.'.xml';
	echo $rest;
	$result = get_external_xml($cache,$rest,$cache_time,1);

	$locations = array();
	$result_count = count($result->xml->Response);
	
	if (($result_count != 0) AND ((integer)$result->xml->Response->Status->code == 200)) {
	foreach ($result->xml->Response as $item) {	
		$location = new StdClass;
		$gps = explode(",", (string)$item->Placemark->Point->coordinates);
		
		$location->gps->lat = (float)$gps[1];
		$location->gps->lng = (float)$gps[0];
		$location->gps->short_lat = round($gps[1],3);
		$location->gps->short_lng = round($gps[0],3);
		$location->gps->space_string = $gps[1]." ".$gps[0];
		$location->gps->comma_String = $gps[1].",".$gps[0];		

		
		if(isset($item->Placemark->ExtendedData->LatLonBox)){
			$attrs = $item->Placemark->ExtendedData->LatLonBox->attributes();
			$location->box->north = (float)$attrs['north'];
			$location->box->south = (float)$attrs['south'];					
			$location->box->east = (float)$attrs['east'];					
			$location->box->west = (float)$attrs['west'];										
		}
		
		$attrs = $item->Placemark->AddressDetails->attributes();		
		$location->details->accuracy = (integer)$attrs['Accuracy'];	
		
		$location->details->address = (string)$item->Placemark->address;
		
		if(isset($item->Placemark->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->Locality->LocalityName)){
			$location->details->localityname = (string)$item->Placemark->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->Locality->LocalityName;
		} elseif (isset($item->Placemark->AddressDetails->Country->AdministrativeArea->Locality->LocalityName)){
			$location->details->localityname = (string)$item->Placemark->AddressDetails->Country->AdministrativeArea->Locality->LocalityName;
		}		
		
		if(isset($item->Placemark->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea)){
			$location->details->sub_admin_area_name = (string)$item->Placemark->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->SubAdministrativeAreaName;
		}	
		
		if(isset($item->Placemark->AddressDetails->Country->AdministrativeArea)){
			$location->details->admin_area_name = (string)$item->Placemark->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;
		}	

		$location->details->countryname = (string)$item->Placemark->AddressDetails->Country->CountryName;
		$location->details->countrycode = strtolower((string)$item->Placemark->AddressDetails->Country->CountryNameCode);
			
		$locations[] = $location;
		
	}
	
	$nh_get_coordinates = $locations;
	return $nh_get_coordinates;

	} else { 
		return false;
	}
}

/*
	Main Plug-in Action
	====================================================================================================
	This is the real deal
*/

 
function smarty_cms_function_nh_api_geocoder($params, &$smarty) {

	if (isset($params['cache_root']) AND ($params['cache_root'] != '')) {	
		$cache_root = $params['cache_root'];
	} else {
		$cache_root = "tmp/cache/";
	}
	
	if (isset($params['cache_time']) AND ($params['cache_time'] != '')) {	
		$cache_time = (integer)$params['cache_time'];
	} else {
		$cache_time = 8640000;
	}	
	
	if (isset($params['api_key']) AND ($params['api_key'] != '')) {		
		$api_key = $params['api_key'];	
	} else {$api_key = '';}
	
	if (isset($params['sensor']) AND ($params['sensor'] == true)) {	
		$sensor = $params['sensor'];
	} else {
		$sensor = false;
	}
	
	if (isset($params['location']) AND ($params['location'] != '')) {		
		$location = $params['location'];	
	} else {
		$location = 'Central Parc, New York';
	}
	
	if (isset($params['language']) AND ($params['language'] != '')) {		
		$language = $params['language'];	
	} else {
		$language = 'en';
	}
	
	$smarty->assign('geoinfo', nh_get_coordinates($cache_root,$cache_time,$api_key,$sensor,$location,$language));
	
return;
}

function smarty_cms_help_function_nh_api_geocoder() {
?>

<p style="color:#ff0000;">ATTENTION: You need the nh_api_essentials plug-in for this plug-in to work! If you experience problems, check if you have the newest version is installed. Currently, at least version 0.3 is required. <br/> This message is always displayed and does not indicate any existing problem :)</p>
<h3>What can NH API GEOCODER do for you?</h3> 
<p>Version of this plug-in: 0.2</p>
<p>This API Collection plug-in allows you to query the google maps geocoder xml API. The plug-in will return a smarty array contaning various information about a single result. <strong>The primary target is to convert an address or location into GPS coordinates.</strong></p>
<p>The plug-in utilizes caching that be configured to match your update frequency desires. To prevent your CMS from hammering the Google API the default caching time is set to 8,640,00 seconds (100 days). The caching also improves site speed as the systems doesn't have to ask for new data over the internet prior to page delivery each time a page containing the plug-in is requested.</p>
<p>Depending on your servers connection, the Geocoder API load as well as complexity of search, calculate with roughly 0.3 - 0.8 seconds for requests of new data. Once the data is cached, page generation times drop by only ~ 0.04 seconds (measured on average configured shared webhost in Germany).</p>
<p>This plug-in <em>does not provide any templates or forms</em> itself, it just provides a plug-in you can call that will return smarty data for maximum flexibility. </p>
<h3>You might want to know this</h3>
<p><ul>
<li>-> You can use the tag for <strong>different gecoder results</strong> within the site and the same page as the cached file is associated to the queried location.</li>
<li>-> <strong>You need a google maps API key for this to work. Go here: http://code.google.com/apis/maps/signup.html</strong></li>
<li>-> Currently, it is not possible to reverse geocode (get address for coordinates)!</li>
</ul>
</p>
<p>---</p>
<h3>Parameters:</h3>

<h4>cache_time</h4>
<p>Time-to-live sets the maximum age of the cache (in seconds). If the cached data is older it will request new feed data. The value should at least be around the thousands (seconds) to avoid your CMS being blocked (I mean... how often does a location change...?). <strong>Default value is 100 days (8640000).</strong>.</p>
<p>{nh_api_geocoder  ... cache_time=8640000 ... }</p>

<h4>cache_root</h4>
<p>Cache_root can be used to define another directory for storage of your youtube xml data. Make sure that the CMS can write the directory you state here! Make sure your path has a trailing slash! Default value is "tmp/cache/" - the standard CMSMS cache folder than can be cleared via the admin panel.</p>
<p>{nh_api_geocoder  ... cache_root='some_dir/some_where/' ... }</p>

<h4>api_key</h4>
<p>Use this parameter to state the key you got for your site.</p>
<p>{nh_api_geocoder  ... api_key='sdfhqw39272420482vsv67sa6sd' ... }</p>

<h4>sensor</h4>
<p>Use this parameter to state where the location request is comming from. Does the device have a GPS device? Default is false. Google wants to know whether the data is potentially used for location based services.</p>
<p>{nh_api_geocoder  ... sensor=false ... }</p>

<h4>location</h4>
<p>Use this parameter to state the lcoation you'd like to look up via. Takes a lot of input options. Basically, what you can enter on http://maps.google.com work with this plug-in.</p>
<p>{nh_api_geocoder  ... location='YOUR ADDRESS' ... }</p>

<h4>language</h4>
<p>Use a two letter country code to define your preferred output language. Please note that the API may not always be able to supply your preferred language and may deliver something else.</p>
<p>{nh_api_geocoder  ... language='en' ... }</p>


<p>---</p>
<h3>Smarty Data Structure </h3>
<p>Below a description of how the data is structured. Behind the "----" - you find a brief description about the single data field.</p>
<p><code>	
n = integer<br /><br />

$geoinfo [n] -> gps -> lat ---- Latitude of position (e.g 53.1234567)<br />
$geoinfo [n] -> gps -> lng ---- Longitude of position<br />
$geoinfo [n] -> gps -> short_lat ---- Latitude in short (e.g 53.123) <br />
$geoinfo [n] -> gps -> short_lng ---- Longitude in short<br />
$geoinfo [n] -> gps -> space_string ---- Coordinates String (e.g. "123.124 15.231466")<br />
$geoinfo [n] -> gps -> comma_string ---- Coordinates String (e.g. "123.124,15.231466")<br /><br />

$geoinfo [n] -> box -> north ---- bounding box of geocoded location (address, city... etc)<br />
$geoinfo [n] -> box -> south <br />
$geoinfo [n] -> box -> east <br />
$geoinfo [n] -> box -> west<br /><br />

$geoinfo [n] -> details -> accuracy ---- Accuracy level of address (9-1) <br />
$geoinfo [n] -> details -> address ---- Street Address of location<br />
$geoinfo [n] -> details -> localityname ---- Usually this is the Cityname<br />
$geoinfo [n] -> details -> sub_admin_area_name ---- This depends on the location, city district or county<br />
$geoinfo [n] -> details -> admin_area_name ---- Usually a federal state, large admin district<br />
$geoinfo [n] -> details -> countryname ---- name of the country<br />
$geoinfo [n] -> details -> countrycode<br />

<p>---</p>

<h3>A simple implementation could look like that:</h3>

{nh_essentials}<br />
{nh_api_geocoder location="1600 Amphitheatre Parkway, Mountain View, CA" api_key="YOUR API KEY"}<br /><br />
The object is located here: {$geoinfo[0]->gps->space_string}<br />

<p>---</p>
<h3>Check the WIKI for updated information. Use the help-link on top of this page :)</h3>
<p>---</p>
<p>Author: Nils Haack &lt;hello@opticalvalve.com&gt;</p>
<p>Version: 0.2 (January 2009)</p>
<p>Change History:<br />
<ul>
<li>0.2 rewrite</li>
<li>0.1 Initial version</li>
</ul>
</p>
<?php
}

function smarty_cms_about_function_nh_api_geocoder() {
	?>
<p>Author: Nils Haack &lt;hello@opticalvalve.com&gt;</p>
<p>Version: 0.2 (January 2009)</p>
<p>Change History:<br />
<ul>
<li>0.2 rewrite</li>
<li>0.1 Initial version</li>
</ul>
</p>
	<?php
}

?>