uniapp: Locate the current position and calculate the distance between two coordinates

1. Get coordinates

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

2. Coordinate conversion address

    Apply for Tencent map key value

    Download the qqmap-wx-jssdk.js file

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. Calculate the distance between coordinates

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); 
				
			}
		});
	}
});

The WeChat applet needs to enable the getLocation permission in the background of the applet

Guess you like

Origin blog.csdn.net/Ygaidi/article/details/130985200