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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…