Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>');
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
202 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...