March 31, 2012

How to calculate driven distance using latitude & longitude in php?

Question by hazem

Given something like this:

//$unit="K";
//$unit="m";

$driven_distance ($lat1, $lng1, $lat2, $lng2, $unit);

How I can I get the time between these two points?

Answer by Starx

A pick out function [Source]

function getDistance($latitude1, $longitude1,
$latitude2, $longitude2, $unit = 'Mi')
{
   $theta = $longitude1 - $longitude2;
   $distance = (sin(deg2rad($latitude1)) *
   sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) *
   cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
   $distance = acos($distance);
   $distance = rad2deg($distance);
   $distance = $distance * 60 * 1.1515;
   switch($unit)
   {
      case 'm': break;
      case 'K' : $distance = $distance *1.609344;
   }
   return (round($distance,2));
}

This functions rounds the result to two decimal places.

Now use exatly the way you are using

$driven_distance = getDistance($lat1,$lng1,$lat2,$lng2,$unit);

Update:

If you want to find out the driven distance the best bet is to use google’s geocode api.

$json = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=true_or_false
');
$details = json_decode($json, TRUE);
var_dump($details);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!