[英]Getting Distance between two location using Google API. PHP
I m trying to calculate distance between two location using API key and PHP as well. 我正在尝试使用API密钥和PHP计算两个位置之间的距离。 I tried two different codes that i found online.
我尝试了两个在网上找到的不同代码。 both of them have some sort of problem.
他们两个都有某种问题。
Two codes, the first one has an error message as "This API project is not authorized to use this API.", while the other code doesn't calculate the distance at all. 有两个代码,第一个有错误消息,例如“此API项目无权使用此API。”,而另一个代码根本不计算距离。
Code :1 代号:1
<?php
function getDistance($addressFrom, $addressTo, $unit = ''){
// Google API key
$apiKey = 'my key';
// Change address format
$formattedAddrFrom = str_replace(' ', '+', $addressFrom);
$formattedAddrTo = str_replace(' ', '+', $addressTo);
// Geocoding API request with start address
$geocodeFrom = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddrFrom.'&sensor=false&key='.$apiKey);
$outputFrom = json_decode($geocodeFrom);
if(!empty($outputFrom->error_message)){
return $outputFrom->error_message;
}
// Geocoding API request with end address
$geocodeTo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddrTo.'&sensor=false&key='.$apiKey);
$outputTo = json_decode($geocodeTo);
if(!empty($outputTo->error_message)){
return $outputTo->error_message;
}
// Get latitude and longitude from the geodata
$latitudeFrom = $outputFrom->results[0]->geometry->location->lat;
$longitudeFrom = $outputFrom->results[0]->geometry->location->lng;
$latitudeTo = $outputTo->results[0]->geometry->location->lat;
$longitudeTo = $outputTo->results[0]->geometry->location->lng;
// Calculate distance between latitude and longitude
$theta = $longitudeFrom - $longitudeTo;
$dist = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) + cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
// Convert unit and return distance
$unit = strtoupper($unit);
if($unit == "K"){
return round($miles * 1.609344, 2).' km';
}elseif($unit == "M"){
return round($miles * 1609.344, 2).' meters';
}else{
return round($miles, 2).' miles';
}
}
$addressFrom = 'New Jersey, United States';
$addressTo = 'New York, USA';
// Get distance in km
$distance = getDistance($addressFrom, $addressTo, "K");
echo $distance;
?>
Code :2 - 编号:2-
<?php
$from = "New Jersey, United States";
$to = "New York, USA";
$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;
}
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";
?>
Code 3: 代码3:
<!DOCTYPE html>
<html>
<head>
<title>Calculate the distance between two locations</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<style type="text/css">
.formbg { background-color: #66CCFF; padding: 10px 0 10px 20px; color: #191919;
border-radius: 10px; border: 2px solid #6D0839; width: 780px; margin: 0 auto;
}
label { font-size: 18px; }
h1 {color: #003366;}
</style>
</head>
<body>
<?php
function getRouteDistance($source_adrs, $dest_adrs, $unit){
//Send request and receive json data
$s_geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$source_adrs.'&sensor=false');
$s_latlong = json_decode($s_geocode);
$d_geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$dest_adrs.'&sensor=false');
$d_latlong = json_decode($d_geocode);
//Get latitude and longitude
$lat1 = $s_latlong->results[0]->geometry->location->lat;
$long1 = $s_latlong->results[0]->geometry->location->lng;
$lat2 = $d_latlong->results[0]->geometry->location->lat;
$long2 = $d_latlong->results[0]->geometry->location->lng;
//Calculate distance from latitude and longitude
$theta = $long1 - $long2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344).' KM';
} else {
return $miles.' MI';
}
}
?>
<div class="form-group row formbg">
<?php
if(($_POST['source'] != '') && ($_POST['destination'] != '')) {
$source = $_POST['source'];
$destination = $_POST['destination'];
$unit = $_POST['unit'];
$source_adrs = str_replace(' ', '+', $source);
$dest_adrs = str_replace(' ', '+', $destination);
$distance = getRouteDistance($source_adrs, $dest_adrs, $unit);
if($distance != '') {
echo 'Distance Between <b>'.$source.'</b> and <b>'.$destination.' : </b><b>'.$distance.'</b>'
.'<br/><br/>';
}
}
?>
<form action="" method="post">
<div class="form-group row">
<label class="col-xs-3 col-form-label">Enter Source Address: </label>
<div class="col-xs-5">
<input class="form-control" type="text" name="source" value="" placeholder="Source">
</div>
</div>
<div class="form-group row">
<label class="col-xs-3 col-form-label">Enter Destination Address: </label>
<div class="col-sm-5">
<input class="form-control" type="text" name="destination" value="" placeholder="Destination">
</div>
</div>
<div class="form-group row">
<label class="col-xs-3 col-form-label">Unit: </label>
<div class="col-sm-5">
<select name="unit" class="form-control">
<option value="k">Kilometer</option>
<option value="m">Mile</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-xs-3 col-form-label"> </label>
<div class="col-sm-5">
<input class="btn btn-primary" type="submit" value="Submit"/>
</div>
</div>
</form>
</div>
</body>
</html>
Try this example function: 尝试以下示例函数:
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) *
cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
Units are K->Kilometers, M->Miles or N->Nautical Miles 单位为K->公里,M->英里或N->海里
You can follow the below link and this not require any google API 您可以点击以下链接,而无需任何Google API
https://gist.github.com/bmoren/22470de1cd47410e0902 https://gist.github.com/bmoren/22470de1cd47410e0902
and if you are trying to get distance by location than use Geo Coding API to get lat lng of particular address and than go through with this link 如果您要按位置获取距离,则可以使用Geo Coding API获取特定地址的纬度,然后通过此链接进行操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.