Friday, February 5, 2016

PHP- Get distance between to Zipcodes using google map api

<?php
$zips= array();
$zips[]= 20899;
$zips[]= 20877;

$geocoded = array();
//$serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false";
$serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=country:US|postal_code:%s&sensor=false";

$curl = curl_init();
foreach ($zips as $zip) {
    curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip)));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $data = json_decode(curl_exec($curl));
    $info = curl_getinfo($curl);
    if ($info['http_code'] != 200) {
        // Request failed
    } else if ($data->status !== 'OK') {
        // Something happened, or there are no results
    } else {
        $geocoded[$zip] =$data->results[0]->geometry->location;
    }
}

$latitudeFrom = $geocoded[$zips[0]]->lat;
$longitudeFrom=  $geocoded[$zips[0]]->lng;
$latitudeTo= $geocoded[$zips[1]]->lat;
$longitudeTo= $geocoded[$zips[1]]->lng;

//echo $latitudeFrom.'<br>';
//echo $longitudeFrom.'<br>';
//echo $latitudeTo.'<br>';
//echo $longitudeTo.'<br>';

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;
      }
}

echo distance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, "M") . " Miles<br>";
echo distance1($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, "M") . " Miles<br>";
echo distance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, "K") . " Kilometers<br>";
echo distance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, "N") . " Nautical Miles<br>";



?>

No comments :

Post a Comment