Uniapp实现实时定位,逆向地理编码完成经纬度转换地址

<template>
	<view class="content">
		<view class="text" v-if="address">{{ address }}</view>
		<view v-else>获取位置中...</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				address: '', // 用于存储地址信息
				latitude: 0, // 纬度
				longitude: 0 // 经度
			};
		},
		onLoad() {
			this.getLocation();
		},
		methods: {
			// 获取地理位置的方法
			getLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => { // 使用箭头函数保持this指向
						console.log('纬度:' + res.latitude);
						console.log('经度:' + res.longitude);
						// 可以将获取到的经纬度信息保存到data中,然后在页面上显示
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						this.getAddress(this.latitude, this.longitude); // 获取地址
					},
					fail: () => {
						uni.showToast({
							title: '获取位置失败,将导致部分功能不可用',
							icon: 'none'
						});
					}
				});
			},
			// 根据经纬度获取地址的方法
			getAddress(latitude, longitude) {
				const key = 'e3982bcf082fbe63015fe5034931f117';
				uni.request({
					url: `https://restapi.amap.com/v3/geocode/regeo?key=${key}&batch=false&location=${longitude},${latitude}`,
					method: 'GET',
					success: (res) => {
						if (res.data.status === '1' && res.data.regeocode) {
							let address = res.data.regeocode.formatted_address;

							this.address = address;
						} else {
							console.error('逆地理编码失败');
						}
					},
					fail: () => {
						console.error('请求地址信息失败');
					}
				});
			}
		}
	};
</script>

<style>
	.content {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
	}
</style>

需要传入自己的高德key值:我的应用 | 高德控制台 创建应用 选择web服务来获取key值

注:需要注意经纬度的顺序  先传递经度 再传递纬度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值