uniapp:定位当前位置,计算两坐标之间的距离

1,获取坐标

uni.getLocation({
	type: 'gcj02',
	altitude: true,
	success(res) {
		let latAndLon = {
			ylog: res.longitude,
			mylat: res.latitude
		}
		uni.setStorageSync('latAndLon', latAndLon)
	}
})

2.坐标转换地址

    申请腾讯地图key值

    下载qqmap-wx-jssdk.js文件

var QQMapWX = require('../../components/qqmap-wx-jssdk.js');
	var qqmapsdk = new QQMapWX({
		key: '申请的key值' // 必填
	});
// 定位
getLocationAddress(e) {
	var _this = this;
	uni.showLoading({
		title: '请稍后...'
	})
	uni.getLocation({
		type: 'gcj02',
		success: function(res) {
			console.log('当前位置的经度:' + res.longitude);
			console.log('当前位置的纬度:' + res.latitude);
			qqmapsdk.reverseGeocoder({
				//位置坐标,默认获取当前位置,非必须参数
				// Object格式
				location: {
					latitude: res.latitude,
					longitude: res.longitude
				},
				success: function(locat) { //成功后的回调
					console.log('locat1111111111111', locat);
					uni.hideLoading();
					_this.remark = locat.result.formatted_addresses.recommend;
					 console.log(_this.remark) // 地址
                     //var mks = [];
				},
				fail: function(error) {},
				complete: function(res) {}
			})
		}
	});
},

3.计算坐标之间距离

uni.getLocation({
	type: 'gcj02',
	success: function(res) {
		console.log('当前位置的经度:' + res.longitude);
		console.log('当前位置的纬度:' + res.latitude);
		uni.request({
			url: 'https://apis.map.qq.com/ws/distance/v1/matrix',
			method: 'GET',
			data: {
				mode: 'walking',
				from: res.latitude + ',' + res.longitude, //你当前位置坐标
				to: '116.41,39.91',// 目的地坐标
				key: '申请的key值' //获取key
			},
			success: (res) => {
				console.log(res);
				let hw = res.data.result.rows[0].elements[0].distance; //拿到距离(米)
				if (hw && hw !== -1) {
					if (hw < 1000) {
						hw = hw + 'm';
					}
					//转换成公里
					else {
						hw = (hw / 2 / 500).toFixed(2) + 'km'
					}
				} else {
					hw = "距离太近或请刷新重试"
				}
				console.log(hw); 
				
			}
		});
	}
});

微信小程序要在小程序后台开通getLocation权限

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_木棠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值