4

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?

David
  • 4,027
  • 10
  • 50
  • 102

2 Answers2

20
<?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;
Raja Rama Mohan Thavalam
  • 8,131
  • 2
  • 31
  • 30
  • @RajaRamaMohanThavalam You should state the request LIMIT of the given google map api – Internial Oct 08 '17 at 20:52
  • Keyless access to the Google maps API is now deprecated, so this will no longer work. – Vincent Nov 13 '18 at 03:00
  • You will need to generate a Google maps API key and add "&key=yourkeygoeshere" to the end of the URL for the above code to work. Use this link to create your API Key: http://g.co/dev/maps-no-account – Vincent Nov 13 '18 at 03:09
0

You can use Google Maps API and PHP for calculates the distance between two address.

$addressFrom = 'Insert from address';
$addressTo = 'Insert to address';
$distance = getDistance($addressFrom, $addressTo, "K");
echo $distance;

getDistance() function can be found from here - http://www.codexworld.com/distance-between-two-addresses-google-maps-api-php/

JoyGuru
  • 1,803
  • 20
  • 11