如何计算两个地址之间的距离

时间:2012-10-25 06:20:37

标签: php api openstreetmap street-address

我想计算两点之间的距离。这些要点是地址。

示例:

A点: JFK机场,纽约,纽约,美国

B点: La Guardia,纽约,纽约,美国

现在我想计算距离(通过道路)和A点到B点之间的行程时间。

我该怎么做?是否可以使用谷歌地图API?你会如何处理这个问题?

2 个答案:

答案 0 :(得分:19)

<?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";
?>

注意:上面你需要km和时间h:m格式只需用

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

答案 1 :(得分:1)

您可以使用Google Maps API和PHP计算两个地址之间的距离。

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

getDistance()函数可以在这里找到 - http://www.codexworld.com/distance-between-two-addresses-google-maps-api-php/