计算点到点之间的距离
示例: 计算用户到任意一个门店的距离
代码仅供参考:
<?php
public function distince()
{
//接收用户当前的经纬度,门店的id
$params['latLng'] = $this->request->input('latLng');//用户当前位置所在的经纬度
$params['shop_id'] = $this->request->input('shop_id');//目标门店的id
$distance = $this->userShopDistance($params);
return $distance;
}
/**
* 用户距离门店距离
* @param $params['shop_id','latLng']
*/
public function userShopDistance($params)
{
//通过传过来的shop_id 查找门店的经纬度;
$shop_latlng = $this->SysshopShop->where(['shop_id'=>$params['shop_id']])->get(['latLng'])->toArray();
//取出后经纬度后赋值于变量
$shop_latlng = $shop_latlng[0]['latLng'];//门店的经纬度
if(empty($shop_latlng)){
throw new Exception('门店位置有误', 4004);
}
$mapKey = "XGHBZ-*****-*****-YOUDH-*****-*****";//自己项目 申请调用地图接口的key (我的就不展示了哈)
//拼接访问腾讯地图的url以及参中间的经纬度参数
$url = "https://apis.map.qq.com/ws/distance/v1/matrix/?mode=bicycling&from=" . $shop_latlng . '&to=' . $params['latLng']."&key=" . $mapKey;
//调用腾讯地图接口;
$output = $this->curl($url,[],[],1);//默认返回的是一个json_encode加密的数据
//需要json_decode解密一下
$res = json_decode($output, true);
//看具体返回的数组是什么取相对应的distince;
$distance = $res['result']['rows'][0]['elements'][0]['distance'];
//把数字距离进行换算成公里
$kilometre = number_format($distance/1000, 1);
return $kilometre;
}
/**
* @param $url
* @param bool $params
* @param int $ispost
* @param int $https
* @return bool|string
* curl 调用腾讯地图的接口
*/
public static function curl($url, $params = false, $ispost = 0, $https = 0)
{
$httpInfo = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($https) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
}
if ($ispost) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
if (is_array($params)) {
$params = http_build_query($params);
}
curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);// 此处就是参数的列表,给你加了个?
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
$response = curl_exec($ch);
if ($response === FALSE) {
//echo "cURL Error: " . curl_error($ch);
return false;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
curl_close($ch);
return $response;
}
797

被折叠的 条评论
为什么被折叠?



