uniapp微信小程序获取定位(通过经纬度获取地址)

项目要求首页有个定位功能,但是uni.getLocation在小程序端只能获取到经纬度,拿不到地址
uniapp官网有说明这点:uni.getLocation(OBJECT) | uni-app官网

uniapp微信小程序获取定位(通过经纬度获取地址)_第1张图片 

解决方案如下:

1. 配置manifest.json

uniapp微信小程序获取定位(通过经纬度获取地址)_第2张图片

 2.引入腾讯地图(需要申请key并下载sdk):微信小程序JavaScript SDK | 腾讯位置服务

uniapp微信小程序获取定位(通过经纬度获取地址)_第3张图片 

圈住的5点建议全做,否则可能会出现问题 

第2步不做可能报错:位置转经纬度~此key未开启WebserviceAPI服务功能

3.代码

在需要的页面引入

import QQMapWX from "../static/sdk/qqmap-wx-jssdk.min.js";
onLoad() {

	this.getLocation()   //获取当前定位
			
},
getLocation(){
	const _this = this
	uni.authorize({
		scope: 'scope.userLocation',
		success() {
			let location = {
				longitude: 0,
				latitude: 0,
				province: "",
				city: "",
				area: "",
				street: "",
				address: "",
			};
			uni.getLocation({
				type: 'gcj02',
				geocode: true,
				success: function(res) {
					uni.setStorageSync('latitude', _this.latitude)
					uni.setStorageSync('longitude', _this.longitude)
					location.longitude = res.longitude;
					location.latitude = res.latitude;
					const qqmapsdk = new QQMapWX({
						key: 'PBZBZ-74CE3-7ND3P-3OVWM-HDZIT-QRF23'  //申请的key
					});
					qqmapsdk.reverseGeocoder({
						location,
					    success: function(res) {
							let info = res.result;
							location.province = info.address_component.province;
							location.city = info.address_component.city;
							location.area = info.address_component.district;
							location.street = info.address_component.street;
							location.address = info.address;
							console.log(location);
                        },
					});
				},	
				fail: function(err) {
					uni.showToast({
							title: '获取定位失败',
							icon: 'none'
					})
				}
			})
		}
	})
},

你可能感兴趣的:(uniapp,微信小程序,微信小程序,uni-app,小程序)