Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the distance between two addresses

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?

like image 360
David Avatar asked Dec 01 '22 05:12

David


1 Answers

<?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;
like image 190
Raja Rama Mohan Thavalam Avatar answered Dec 06 '22 10:12

Raja Rama Mohan Thavalam