uniapp 开发微信小程序,获取经纬度(uni.getLocation)并且转化详细地址(‌高德地图逆地理编码API、‌腾讯地图逆地理编码)

发布于:2025-08-03 ⋅ 阅读:(17) ⋅ 点赞:(0)

一、前置配置(manifest.json)

在项目根目录的配置文件中进行配置
在这里插入图片描述

 /* 小程序特有相关 */
    "mp-weixin" : {
        "appid" : "小程序的appId",
        "setting" : {
			// 是否校验请求域名合法性,设为 false 可跳过HTTPS校验(仅限开发环境)
            "urlCheck" : false,
			// 启用ES6语法转ES5的兼容性处理,建议开启以支持现代JS语法
            "es6" : true,
			// 是否启用PostCSS自动补全CSS前缀(如-webkit-),关闭可减少编译时间
            "postcss" : false
        },
		// 指定基础库版本号(如2.21.2),影响小程序可用的API能力和兼容性
        "libVersion" : "2.21.2",
		// 是否启用自定义组件功能,开启后可使用第三方或自定义组件
        "usingComponents" : true,
		// 声明需申请的敏感权限接口列表
        "requiredPrivateInfos" : [ "getLocation", "onLocationChange" ],
		// 定义权限用途描述,用户授权时会显示这些说明
        "permission" : {
			// 首次获取位置时的提示文本(如“用于展示”)
			 "location": {
			    "desc": "获取位置信息用于展示"
			  },
			  // 持续定位的用途说明(如“轨迹记录”)
            "scope.userLocation" : {
                "desc" : "获取位置信息用于展示"
            }
        }
    },

二、实现方式

1、uni.getLocation (简单获取经纬度)

  • uni.authorize:用于‌首次请求权限‌,弹窗询问用户是否允许获取位置
  • uni.openSetting:用于‌跳转系统设置页‌,当用户拒绝授权后引导手动开启权限
  • uni.getLocation:‌实际获取坐标‌,需在权限通过后调用
// 普通仅仅获取经纬度
			getLocationHandle(){
				// 1. 先请求授权
				// uni.authorize:用于‌首次请求权限‌,弹窗询问用户是否允许获取位置
				uni.authorize({
				  scope: 'scope.userLocation',
				  success: () => {
				    // 2. 授权成功后获取高精度坐标
					// uni.getLocation:‌实际获取坐标‌,需在权限通过后调用
				    uni.getLocation({
						// wgs84:国际标准GPS坐标系(原始经纬度数据)
						// gcj02:中国国测局坐标系(高德/腾讯地图专用)
				      type: 'gcj02',
				      // isHighAccuracy: true, //高精度模式(isHighAccuracy:true)会增加功耗,建议按需使用
				      success: (res) => {
						this.location = res.longitude+','+res.latitude;
				        console.log('精确坐标:', this.location);
				      },
				      fail: (err) => {
				        uni.showToast({ title: '获取位置失败' });
				      }
				    });
				  },
				  fail: () => {
				    // 3. 授权被拒时引导用户去设置页
				    uni.showModal({
				      content: '为了正常使用,请授权位置信息!',
				      success: (res) => {
						  // uni.openSetting:用于‌跳转系统设置页‌,当用户拒绝授权后引导手动开启权限
				        if (res.confirm) uni.openSetting();
				      }
				    });
				  }
				});
			
			},

2、高德地图逆地理编码API

uniapp官网
https://uniapp.dcloud.net.cn/api/location/location.html#getlocation
在这里插入图片描述

DCloud社区文章
https://ask.dcloud.net.cn/article/35070
在这里插入图片描述

高德开放平台
https://lbs.amap.com/api/wx/summary
在这里插入图片描述

需先注册高德开发者账号并申请Key,引入高德微信小程序SDK后调用逆地理编码接口
在这里插入图片描述

高德微信小程序SDK
获取到的amap-wx.js文件,可以在项目根目录,创建一个libs文件夹进行存放(但不要放在 static 目录下)
在这里插入图片描述
具体代码实现

// 高德
<script>
	// 高德
	 import amap from '@/libs/amap-wx.130.js';
		export default {
		data() {
			return {
				location: "",
				// 高德
				AMapKey: "你的key",
				 amapPlugin: null,  
			}
		},
		onLoad(option) {
      	this.amapPlugin = new amap.AMapWX({
				key: this.AMapKey
			});
		},
		methods: {
			// 高德:使用高德逆地理编码接口regeo
			// 需在微信小程序后台配置高德域名白名单
			// 高德地图的合法域名为https://restapi.amap.com
			 getRegeo() {
			 uni.showLoading({
			 	title: '获取信息中'
			 });
			 	this.amapPlugin.getRegeo({
			// 		不传递location,默认就是当前的经纬度
			// 		 location: 'XXXXXX,XXXXXX',
					success: (data) => {
		 			console.log(data, 'data高德')
						this.addressName = data[0].name;
						 uni.hideLoading();
			 		}
			 	});
			 },
			
			},
	}
</script>	 
  • 需在微信小程序后台配置高德域名白名单
  • 高德地图的合法域名为https://restapi.amap.com
    在这里插入图片描述
    获取数据
    在这里插入图片描述

3、腾讯地图逆地理编码API

需先注册腾讯开发者账号并申请Key,引入腾讯微信小程序SDK后调用逆地理编码接口
https://lbs.qq.com/dev/console/application/mine
在这里插入图片描述
https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/jsSdkOverview
腾讯微信小程序SDK
获取到的qqmap-wx-jssdk.min.js文件,可以在项目根目录,创建一个libs文件夹进行存放(但不要放在 static 目录下)
在这里插入图片描述

  • 需在微信小程序后台配置腾讯域名白名单
  • 腾讯地图的合法域名为https://apis.map.qq.com
    在这里插入图片描述
    具体代码实现
<script>
var QQMapWX = require('@/libs/qqmap-wx-jssdk.min.js')
		export default {
		data() {
			return {
				location: "",
				// 腾讯
				QQMapKey:'你的key',
			}
		},
		onLoad(option) {
		// 腾讯
			this.getLocation()
		},
			methods: {
				// 腾讯获取当前位置
			// 腾讯地图的合法域名为https://apis.map.qq.com
			getLocation() {
				let _this = this
				uni.authorize({
					scope: 'scope.userLocation',
					success() {
						let location = {
							longitude: 0,
							latitude: 0,
							province: "",
							city: "",
							area: "",
							street: "",
							address: "",
						};
						uni.getLocation({
							type: 'gcj02',
							isHighAccuracy: true, // 增加高精度模式
							geocode: true,
							altitude: true, // 需要海拔数据时可开启
							success: (res) => {
								console.log(res, _this.QQMapKey, '获取经纬度');
								location.longitude = res.longitude;
								location.latitude = res.latitude;
								const qqmapsdk = new QQMapWX({
									key: _this.QQMapKey //腾讯地图申请的key(后续需要公司提供,个人开发者额度有限)
								});
			                    // 腾讯地图逆地理编码
								qqmapsdk.reverseGeocoder({
									location,
									success: function(res) {
										console.log(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) {
								this.$utils.modal({
									content: '获取位置失败,请重新进入小程序并同意获取位置',
									confirmText: '确定',
									showCancel: false,
								}).then(() => {
									uni.openSetting()
								})
			
							}
						})
					},
					fail: () => {
						this.tipsAddress()
					}
				})
			},
			tipsAddress() {
				this.$utils.modal({
					content: '为了正常使用,请授权位置信息!',
					confirmText: '确定',
					showCancel: false,
				}).then(() => {
					uni.openSetting({
						success: (res) => {
							if (res.errMsg === 'openSetting:ok') {
								console.log(res.authSetting, 'res');
								if (!res.authSetting['scope.userLocation']) {
									this.tipsAddress()
								} else {
									this.getLocation()
								}
							}
						},
						fail: () => {
							this.tipsAddress()
						}
					})
				})
			},
			},
	}
</script>	 

获取数据
在这里插入图片描述

三、注意

上述申请的:高德的key和腾讯的key 如果是作为个人开发者申请的(有一定的调用额度限制,不一定能满足正式环境下的需求,正式环境下一般都需要进行额度付费使用。),一般仅仅用于开发环境进行调试,项目正式上线,还是需要使用公司提供的。