uniapp中如何获取当前位置并计算出某个地点距离

uni.getLocation(OBJECT)

获取当前的地理位置、速度。


1.首先在uniapp中的manifest.json配置文件开启获取位置权限来获取当前位置

2.代码块部分

<template>
	<view v-for="(item,index) in dataList" :key='index'>{{item.jl}}</view>
</template>
<script>
	import {index} from '@/api/index.js'   //(要根据根本后端来反馈--虚拟的接口)
	export default {
		data() {
			return {
			   dataList:[],
			   location: {
			   	lat: 0,
			   	lng: 0,
			   },
			}
		},
		mounted() {
			//#ifdef MP-WEIXIN
			this.initPage()
			// #endif 
			
			//#ifndef MP-WEIXIN 
			this.getList()
			// #endif
		},
		methods:{
			//发送请求获取你要得到那个地方的经度纬度(要根据根本后端来反馈--虚拟的接口)
			getList(){
				index().then(res=>{
					this.dataList = res.rows
					this.dataList.forEach(item => {
						var s = this.distance(item.location.split(',')[1], item.location.split(',')[0])   //调用计算方法(经度,纬度)传值
						this.$set(item, 'jl', s)   //把距离存储到dataList中
					})
				})
			},
			
			//获取当前位置
			getLocation() {
				let location = {
					lat: 0,
					lng: 0,
				}
				return new Promise((reserve, reject) => { //因为获取位置是异步接口所以需要使用promise
					uni.getLocation({
						success(res) {
							location.lat = res.latitude
							location.lng = res.longitude,
							reserve(location);
							console.log(res.latitude,res.longitude)
						},
						fail(err) {
							reject(location); //获取失败则返回经纬坐标为0
						}
					})
				})
			},
			//根据金纬度计算距离
				distance(lat1, lng1) {
					var that = this;
					let lat2 = that.location.lat;
					let lng2 = that.location.lng;
					let rad1 = lat1 * Math.PI / 180.0;
					let rad2 = lat2 * Math.PI / 180.0;
					let a = rad1 - rad2;
					let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
					let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) *
						Math.cos(
							rad2) * Math.pow(
							Math.sin(b / 2), 2)));
					s = s * 6378.137;
					s = Math.round(s * 10000) / 10000;
					s = s.toString();
					s = s.substring(0, s.indexOf('.') + 2);
					return s
				},
				initPage: async function() {
					this.location = await this.getLocation()
					this.getList()
				}
		},
		
	}
</script>
  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值