Ask Question

Menu

How to get distance between two Address in PHP


index.php

<!DOCTYPE html>
<html>
<body>
<form method="post" action="test.php">
Source address :<br>
<input type="text" name="start">
<br>
Destination address:<br>
<input type="text" name="destination">
<br>
<br>
<input type="submit" name="save" value="submit">
</form>
</body>
</html>

test.php

<?php
if(isset($_POST['save']))
{
$start = $_POST['start'];
$destination = $_POST['destination'];
$apiUrl = 'http://maps.googleapis.com/maps/api/directions/json';
$url = $apiUrl . '?' . 'origin=' . urlencode($start) . '&destination=' . urlencode($destination);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($curl);
if(curl_errno($curl)){
throw new Exception(curl_error($curl));
}
curl_close($curl);
$json = json_decode(trim($res), true);
$route = $json['routes'][0];//Automatically select the first route that Google gave us.
$totalDistance = 0;//Loop through the "legs" in our route and add up the distances.
foreach($route['legs'] as $leg){
$totalDistance = $totalDistance + $leg['distance']['value'];
}
//Divide by 1000 to get the distance in KM.
$totalDistance = round($totalDistance / 1000);
echo 'Total distance is ' . $totalDistance . 'km';
}
?>










Subscribe