How to calculate the distance between two addresses

David picture David · Oct 25, 2012 · Viewed 20.5k times · Source

I would like to calculate the distance between two points. The points are addresses.

Example:

Point A: JFK Airport, New York, NY, United States

Point B: La Guardia, New York, NY, United States

Now I want to calculate the distance (via roads) and the travel time between point A and point B.

How can I do that? Is it possible to use google maps API? How would you approach the problem?

Answer

Raja Rama Mohan Thavalam picture Raja Rama Mohan Thavalam · Nov 22, 2013
<?php 
$from = "sr nagar,hyderabad";
$to = "kukatpalle,hyderabad";
$from = urlencode($from);
$to = urlencode($to);
$apiKey= "";  
$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&key=$apiKey&language=en-EN&sensor=false");
$data = json_decode($data);
$time = 0;
$distance = 0;
foreach($data->rows[0]->elements as $road) {
    $time += $road->duration->value;
    $distance += $road->distance->value;
}
echo "To: ".$data->destination_addresses[0];
echo "<br/>";
echo "From: ".$data->origin_addresses[0];
echo "<br/>";
echo "Time: ".$time." seconds";
echo "<br/>";
echo "Distance: ".$distance." meters";
?>

Note : above you need to km and time h:m format just replace with

$time      = $road->duration->text;
$distance  = $road->distance->text;