实现定位距离,点击跳转地图
做成组件方便调用
wxml
<view class="distance-navigator" style="{{distanceNavStyle}}" bindtap="markerTap">
<text class="distance">{{distance}}KM</text>
</view>
js
properties: {
marker: {
type: Object
},
showNav: {
type: Boolean,
value: true
},
distanceNavStyle: {
type: String,
value: 'bottom: 0; right: 30rpx;'
}
},
/**
* 组件的方法列表
*/
methods: {
markerTap(e) {
console.log( this.data.marker,'000');
const latitude = Number(this.data.marker.latitude);
const longitude = Number(this.data.marker.longitude);
// 获取标记信息
// const {latitude, longitude} = this.data.marker
// 打开地图 App 进行导航
wx.openLocation({
latitude,
longitude
});
console.log('---000');
},
getLocationAndDistance () {
let that = this;
const {latitude: targetLatitude, longitude: targetLongitude} = that.data.marker;
try {
wx.getFuzzyLocation({
type: 'wgs84', // 使用 GPS 坐标
success(res) {
// 这里可以将用户的位置坐标保存到数据中或进行其他操作
const userLatitude = res.latitude; // 用户当前纬度
const userLongitude = res.longitude; // 用户当前经度
that.getDistance(userLatitude, userLongitude, targetLatitude, targetLongitude);
},
fail(err) {
// 获取位置失败时的处理逻辑
console.error('获取位置失败', err);
}
});
} catch {
// 获取不到经纬度时默认北京
const userLatitude = 39.90965; //纬度
const userLongitude = 116.40418; //经度
that.getDistance(userLatitude, userLongitude, targetLatitude, targetLongitude);
};
},
getDistance (lat1, lon1, lat2, lon2) {
const R = 6371; // 地球的半径,单位千米
const dLat = this.deg2rad(lat2 - lat1);
const dLon = this.deg2rad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = R * c; // 距离(单位:千米)
this.setData({
distance: distance.toFixed(2)
});
return distance;
},
deg2rad (deg) {
return deg * (Math.PI / 180);
}
}