<?php
   
/*
   Distance Calculator by Alex Figueroa
    www.thelostfaith.net
    
    Free for any usage you'd like, not necessary but
    a link to my site wouldn't be any harm. 
    */

class calculateDistance {
      
    function 
produceDataset($dArr) {      
        
        
//$dArr must be in a array(lat1,lon1,lat2,lon2...) format.
        // the end result with this function is array(array(lat1,lon1,lat2,lon2),array(lat2,lon2,lat3,lon3))
        // this will allow us to calculate point-to-point distances.
        
$dArrChunk array_chunk($dArr,4);
        
$chunkCount count($dArrChunk);  
        
$dArrCount count($dArr);
        for(
$i=0$i<$dArrCount$i++) {
            
// building $pArr will ultimately request a key greater than $dArrCount, so to prevent
            // a catastrophic failure later when it comes to calculating, we have to throw the if/else
            
if(($i+$dArrCount) || ($i+$dArrCount)) continue;
            else {
                
$pArr[] = array(array($dArr[$i],$dArr[($i+1)]),array($dArr[($i+1)],$dArr[($i+2)]));
            }
        }
        
        
// $pArr will return array(array(lat1,lon1,lat2,lon2),array(lat2,lon2,lat3,lon3)...)
        //return $dArrChunk;
        
        
$aChunk array_chunk($pArr,2);
        
$aCount count($aChunk);
        for(
$i=0$i<$aCount$i++) {
            
$tempArr $aChunk[$i];
            
$aMerge[] = array_merge($tempArr[0],$tempArr[1]);
        }
        
        
//return $aMerge;
        
        
$mCount count($aMerge);
        for(
$i=0$i<$mCount$i++) {
            
$tempArr $aMerge[$i];
            
$mArr[] = array($tempArr[0],$tempArr[3]);
        }
        
        
//return $mArr;
        
        
$mCount count($mArr);
        for(
$i=0$i<$mCount$i++) {
            
$tempArr $mArr[$i];
            
$tArr[] = array_merge($tempArr[0],$tempArr[1]);
        }
        
        
//return $tArr;
          
        
$tCount count($tArr);
        for(
$i=0$i<$tCount$i++) {
            
$rArr[] = $this->getDistance($tArr[$i]);
        }
          
        return 
$rArr;
    }
        
    function 
getDistance($latLonArr) {
        
$earthRadius 6371;
        
$km2mi .62137;
          
        
$lat1 =  $latLonArr[0];
        
$lon1 $latLonArr[1];
        
$lat2 $latLonArr[2];
        
$lon2 $latLonArr[3];
          
        
$deltaLat $lat2-$lat1;
        
$deltaLon $lon2-$lon1;
         
        
$alpha $deltaLat/2;
        
$beta $deltaLon/2;
          
        
$a sin(deg2rad($alpha))*sin(deg2rad($alpha)) +
            
cos(deg2rad($lat1))*cos(deg2rad($lat2)) *
            
sin(deg2rad($beta)) * sin(deg2rad($beta));
            
        
$c asin(min(1,sqrt($a)));
          
        
$distance 2*$earthRadius*$c;
          
        return 
round(($distance*$km2mi),2); /*for mi*/
        //return "(".$lat1.",".$lon1." - ".$lat2.",".$lon2.") ".round(($distance*$km2mi),2)."=>".round($distance,2); /*for km*/
    
}
}
?>