使用PHP/Google地图计算距离 [英] Using PHP/Google Maps to Calculate Distances

查看:88
本文介绍了使用PHP/Google地图计算距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的(或者我认为是)PHP/Google Maps函数,该函数可以让我计算两个地址之间的距离.我是PHP的新手,这是到目前为止的内容,但是出了点问题.

I'm trying to create a simple (or so I thought) PHP/Google Maps function which would allow me to calculate a distance between two addresses. I'm new to PHP, and here's what I've got so far, however, something's wrong.

<section class="group">

        <label for="start">Start:</label>
        <input type="text" name="start" id="start" value="" />

        <label for="finish">Finish</label>
        <input type="text" name="finish" id="finish" value="" />

        <input type="button" value="Calculate distance" id="calculate-distance" />

        <div id="results"></div>

    </section>

    <?php
    function getLatLong($address) {

    $address = str_replace(' ', '+', $address);
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$address.'&sensor=false';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $geoloc = curl_exec($ch);

    $json = json_decode($geoloc);
    return array($json->results[0]->geometry->location->lat,
    $json->results[0]->geometry->location->lng);

    }

    function Haversine($start, $finish) { 

    $theta = $start[1] - $finish[1];
    $distance = (sin(deg2rad($start[0])) * sin(deg2rad($finish[0]))) + (cos(deg2rad($start[0])) * cos(deg2rad($finish[0])) * cos(deg2rad($theta)));
    $distance = acos($distance);
    $distance = rad2deg($distance);
    $distance = $distance * 60 * 1.1515;

    return round($distance, 2);
     }

    $start = getLatLong('start');
    $finish = getLatLong('finish');

    $distance = Haversine($start, $finish);

    print('<p>The distance between ['.$start[0].', '.$start[1].'] and   ['.$finish[0].',    '.$finish[1].'] is '.$distance.' miles ('.($distance * 1.609344).'  km).</p>');
?>

推荐答案

<?php
$from = "erode";
$to = "Chennai";

$from = urlencode($from);
$to = urlencode($to);

$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&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;
}
$km=$distance/1000;
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";
echo "<br/>";
echo $km;
?>

这篇关于使用PHP/Google地图计算距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆