uniapp获取当前位置+通过逆地理编码用经纬度得到具体位置

先用uni.getLocation(OBJECT)获取当前的地理位置:

<template>
	<view class="map-box">
		<map id="map" :latitude="latitude" :longitude="longitude" scale="14" show-location style="width: 100%;"></map>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		defineEmits
	} from 'vue'
	const props = defineProps(['parentValue'])
	const emit = defineEmits(['onPosition'])

	const latitude = ref(0);
	const longitude = ref(0);

	const getCurrentLocation = () => {
		uni.getLocation({
			type: 'gcj02', // 返回可以用于 uni.openLocation 的坐标
			success: (res) => {
				longitude.value = res.longitude;
				latitude.value = res.latitude;
				emit("onPosition", {
					'longitude': longitude.value,
					'latitude': latitude.value
				})
			},
			fail: (err) => {
				console.error('获取位置失败', err);
			}
		});
	}
	onMounted(() => {
		getCurrentLocation();
	});
</script>

<style scoped lang="scss">
	.map-box {
		display: block;
		width: 100%;
	}
</style>

开始前确保你已经注册并获得了高德地图API的密钥。可以在高德地图开放平台注册并获取密钥。这个密钥将用于访问地图服务。

如果需要具体地址可以直接拿res.data.regeocode.formatted_address里的数据,也可以用res.data.regeocode.addressComponent里面的数据自己拼接:

// 逆地理编码
export async function getAddressByCoordinate(position) {
	const {
		longitude,
		latitude
	} = position
	const key = 'xxxxxx'; // 高德地图key
	const url = `https://restapi.amap.com/v3/geocode/regeo?key=${key}&location=${longitude},${latitude}`;

	try {
		const data = await new Promise((resolve, reject) => {
			uni.request({
				url,
				success: (res) => {
					// console.log(res.data.regeocode);
					if (res.data && res.data.regeocode) {
						const {
							province,
							city,
							district,
							township,
							streetNumber
						} = res.data.regeocode.addressComponent
						let temp = province + city + district + township + streetNumber.street + streetNumber.number
						return resolve(temp)
					}
				},
				fail: (error) => {
					reject(error)
				}
			});
		})
		return data
	} catch (error) {
		console.error(error)
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值