uni-app:在小程序中判断用户当前定位与指定位置之间的距离

1、HTML部分

<view @click="clickToShopping()">开始买菜</view>

2、js部分

async clickToShopping() { //点击开始买菜按钮,判断是否在用户家2km范围内
	var that = this;
	// 1、调接口,取目的地的经纬度。
	that.userLanLong = await that.getUserLanlong(that.obj.serviceOrderId); 
	// console.log(that.userLanLong);
	
	// 2、取服务人员当前的经纬度
	uni.getLocation({
		type: 'gcj02',
		success: (res) => {
			const latitude = res.latitude;
			const longitude = res.longitude;
			// console.log("设备定位:",latitude,longitude);
			
			// 3、判断距离目的地的范围
			// latitude1,longitude1,latitude2,longitude2
			const dist = that.distance(parseFloat(that.userLanLong.userlatItud), parseFloat(that.userLanLong.userLongItude),latitude, longitude);
			
			if (parseFloat(dist) > 2) { //范围要在2KM内
				CtrolUI.toast('请在用户家2km范围内!')
			} else {
				that.$refs.shoppingPopup.open(); //打开开始买菜弹窗
			}
		},
		fail: () => {
			CtrolUI.toast('获取当前设备的经纬度失败!')
		}
	})
},

3、src/publicFun.js文件里的 getUserLanlong()、distance() 函数。

import api from '@/apiConfig/api.js'

let base={};
base.install = function(Vue,options){
	Vue.prototype.getUserLanlong = async function(id){//通过服务单ID查询用户经纬度
		return new Promise((resolve, reject) => {
			api.getUserLanLong({
				serviceOrderId : id
			}).then(function (res) {
				// console.log(res);debugger
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		})
	}
	Vue.prototype.distance = function(la1, lo1, la2, lo2){
		/**
		   * 由经纬度计算两点之间的距离,la为latitude缩写,lo为longitude
		   * @param la1 第一个坐标点的纬度
		   * @param lo1 第一个坐标点的经度
		   * @param la2 第二个坐标点的纬度
		   * @param lo2 第二个坐标点的经度
		   * @return (int)s   返回距离(单位千米或公里)
		   * @tips 注意经度和纬度参数别传反了,一般经度为0~180、纬度为0~90
		   * 具体算法不做解释,有兴趣可以了解一下球面两点之间最短距离的计算方式
		   */
		var La1 = la1 * Math.PI / 180.0;
		var La2 = la2 * Math.PI / 180.0;
		var La3 = La1 - La2;
		var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
		s = s * 6378.137;
		s = Math.round(s * 10000) / 10000;
		s = s.toFixed(2);
		return s;
	}
};
export default base;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值