我正在使用代码获取两点之间的距离,效果很好,但是问题是代码返回的数据带有KM个字符(例如56.0 km),因此我想使用纯数字将其获取为Mile或用它与其他值进行比较
public function getdistance(Request $request)
{
$currentaddress =$request->currentadd;
$from = '4429 North Broadway, Chicago, IL, United States';
$remFrom = str_replace(',', '', $from); //Remove Commas
$from = urlencode($remFrom);
$to = $currentaddress;
$remTo = str_replace(',', '', $to); //Remove Commas
$to = urlencode($remTo);
$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,true);
$distance = $data['rows'][0]['elements'][0]['distance']['text'];
return response()->json([$distance]);
}
答案 0 :(得分:2)
您可以在API URL中指定units
parameter,以使用英制单位(英尺和英里)代替公制。来自文档的注意事项:
此单位制设置仅影响在距离字段中显示的文本。距离字段还包含始终以米表示的值。
http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false&units=imperial
答案 1 :(得分:0)
使用$distance = $data['rows'][0]['elements'][0]['distance']['value'];
,这将是距离,以米为单位。
您可以用1609.34
除以将其转换为英里。
响应(针对this request):
{
"destination_addresses" : [ "New York, NY, USA" ],
"origin_addresses" : [ "4429 North Broadway, Chicago, IL 60640, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,294 km",
"value" : 1293988 // <============ distance in meters
},
"duration" : {
"text" : "12 hours 24 mins",
"value" : 44618 // <============ duration in seconds
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}