前端wxml代码:
<button bindtap="where">获取目的地位置</button>
<button bindtap="here">获取当前位置</button>
<button bindtap="getdistance">计算距离</button>
前端js代码:
//获取目的地经纬度缓存起来
where() {
// chooseLocation
wx.chooseLocation({
latitude: 0,
success(res) {
//目的地经度
wx.setStorageSync('toLongitude',res.longitude )
//目的地纬度
wx.setStorageSync('toLatitude',res.latitude )
}
})
},
//通过api获取当前经纬度缓存起来
here() {
wx.getLocation({
altitude: 'altitude',
success(res) {
//当前经度
wx.setStorageSync('hereLongitude',res.longitude )
// wx.getStorageSync('hereLongitude')
//当前纬度
wx.setStorageSync('hereLatitude',res.latitude )
wx.showToast({
title: '获取成功',
})
}
})
},
//调用函数获取距离
getdistance()
{
//将缓存起来的当期和目的地经纬度取出来发送到后端调用腾讯接口后返回距离给前端
//所在经度
let hereLongitude=wx.getStorageSync('hereLongitude');
//所在纬度
let hereLatitude=wx.getStorageSync('hereLatitude');
//目的地经度
let toLongitude=wx.getStorageSync('toLongitude');
//目的地纬度
let toLatitude=wx.getStorageSync('toLatitude');
wx.request({
url: 'http://www.exam.com/api/distance',
data:{
hereLongitude:hereLongitude,
hereLatitude:hereLatitude,
toLongitude:toLongitude,
toLatitude:toLatitude
},
dataType:'json',
success(res)
{
let distance=res.data.data.result.rows[0].elements[0].distance;
//打印距离
}
})
},
后端代码:
public function distance(Request $request)
{
$all=$request->all();
//当前纬度
$hereLatitude=$all['hereLatitude'];
//经度
$hereLongitude=$all['hereLongitude'];
//目的地纬度
$toLatitude=$all['toLatitude'];
//目的地经度
$toLongitude=$all['toLongitude'];
$url="https://apis.map.qq.com/ws/distance/v1/matrix";//请求接口
$key="";//申请的key
$from=$hereLatitude.','.$hereLongitude;
$to=$toLatitude.','.$toLongitude;
$mode="driving";
$url=$url.'?key='.$key.'&from='.$from.'&to='.$to.'&mode='.$mode;
$result= json_decode(file_get_contents($url),true);
return ['code'=>200,'mes'=>'接收成功','data'=>$result];
}