Friday, September 2, 2011

Calculate Postal Code Distance Using Google API


This is simple function to calculate the distance between two different Canadian postal codes.

$query = "http://maps.google.co.uk/maps/geo?q=".urlencode($code)."&output=json&key=".$mapsApiKey;

 For this i used http://maps.google.co.uk- (use domian nearest your region)
<?php

/**
 * @author jayje
 * @copyright 2011
 */




$add1=getLatLong('L8R 3L4');
$add2=getLatLong(10001);
$lat1=$add1['Latitude'];
$lon1=$add1['Longitude'];

$lat2=$add2['Latitude'];
$lon2=$add2['Longitude'];

echo "<br>kilometers=";
echo distance($lat1, $lon1, $lat2, $lon2, 'k');

 function getLatLong($code){
 $mapsApiKey = 'ABQIAAAA8JnBykA-EPiMmKdOR--UcRT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQ8npfo6U4N7PRuya0RBiyaKD8mRA';
 $query = "http://maps.google.co.uk/maps/geo?q=".urlencode($code)."&output=json&key=".$mapsApiKey;

 $data = file_get_contents($query);
 // if data returned
 if($data){
  // convert into readable format
  $data = json_decode($data);
  $long = $data->Placemark[0]->Point->coordinates[0];
  $lat = $data->Placemark[0]->Point->coordinates[1];
  return array('Latitude'=>$lat,'Longitude'=>$long);
 }else{
  return false;
 }
}
function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

?>

Smarty split a String

$item ='FFFEREE-TGFFGGF-RERR'

This is the can used to split smarty variable.

{assign var="bar_at" value=$item|strpos:"-"}
 <li>{$item}</li>
 <li>{$item|substr:0:$bar_at}</li>
<li>{$item|substr:$bar_at+1}</li>