uniapp 微信小程序开发使用高德地图、腾讯地图

一、高德地图

1.注册高德地图开放平台账号

(1)创建应用

这个key 第3步骤,配置到项目中locationGps.js

2.下载高德地图微信小程序插件

(1)下载地址

高德地图API | 微信小程序插件

(2)引入项目中

3. 创建逆地理编码js文件

(1)locationGps.js

javascript 复制代码
/** 使用第三方地图逆地址解析经纬度获取用户当前所在位置信息
 * @param {Number} lat
 * @param {Number} lng
 */
 
export const getUserCurrentLocationInfo = (lat, lng) => {
    var GDMapWX = require('../assets/GD/amap-wx.130.js');
    var GDMapSdk = new GDMapWX.AMapWX({
        key: '' // 必填  高德应用key
    });
    return new Promise((resolve, reject) => {
        GDMapSdk.getRegeo({
            location: lng + ',' + lat,
            success: res => {
                if (res && res.length > 0) {
                    resolve(res); // 确保返回的结果是一个数组
                } else {
                    reject('No data returned');
                }
            },
            fail: function(error) {
                reject(error);
            }
        });
    });
}

(2)存放位置

4. 前端代码

javascript 复制代码
<script>
import {
	getUserCurrentLocationInfo
} from "@/utils/locationGps.js"; // 引入函数


data(){

    return {
    	    latitude: 0, // 纬度,范围为-90~90,负数表示南纬,使用 gcj02 国测局坐标系
			longitude: 0, // 经度,范围为-180~180,负数表示西经,使用 gcj02 国测局坐标系
			city: '',
			address: '',

        }
    }


methods:{
        // 定位
		getLocation() {
			// 使用 uni.getLocation 获取经纬度
			uni.getLocation({
				type: 'gcj02', // 使用国测局坐标系 wgs84
				success: (res) => {
					console.log('经度:', res.longitude);
					console.log('纬度:', res.latitude);
					console.log('速度:', res.speed);
					console.log('精度:', res.accuracy);
					this.latitude = res.latitude;
					this.longitude = res.longitude;
					this.getLocationInfo(res.latitude, res.longitude); 
				},
				fail: (err) => {
					console.error('获取位置失败', err);
				}
			});
		},
		// 使用高德地图 API 进行逆地理编码
		getLocationInfo(lat, lng) {
			getUserCurrentLocationInfo(lat, lng)
				.then((res) => {
					this.city = res[0].regeocodeData.addressComponent.city || res[0].regeocodeData.addressComponent
						.province;
					this.address = res[0].regeocodeData.formatted_address;
					console.log('城市:', this.city);
					console.log('详细地址:', this.address);
				})
				.catch((error) => {
					console.error('逆地理编码失败', error);
				});
		},
	},
	mounted() {
		this.getLocation();
	},

二、腾讯地图

1.注册腾讯地图开放平台账号

(1)创建应用

腾讯地图开放平台

(2)前端代码

将应用key配置到前端代码中

javascript 复制代码
<template>
	<view>
		<view class="title">当前位置:<text style="font-weight: bold;">{{address}}</text></view>
		<button @click="locationn">点击获取当前位置</button>
	</view>
</template>


<script>
	export default {
		data() {
			return {
				longitude: null,
				latitude: null,
				address: ""
			}
		},
		onLoad() {
			this.location()
		},
		methods: {

			location() {
				var that=this
				uni.getFuzzyLocation({
					success: function(res) {
						that.longitude=res.longitude
						that.latitude=res.latitude
					},
				});
			},
			locationn() {
				console.log(this.longitude)
				console.log(this.latitude)
				uni.request({
					url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${encodeURIComponent(this.latitude)},${encodeURIComponent(this.longitude)}&key=E7XBZ-FUXC7-D22XZ-POFT7-OD5LJ-6RBAV&get_poi=1`,
					method: 'GET',
					success: (res) => {
						console.log(res)
						this.address=res.data.result.ad_info.city
					}
				})

			}
		}
	}
</script>

<style>
	.title {
		display: inline-block;
		margin: 20px;
		font-size: 20px;
	}
</style>

在onLoad生命周期函数中,调用getFuzzyLocation方法来获取经纬度;

再把经纬度赋给data的数据中,触发调用腾讯地图API,把我想要的值赋给address,最后在template中进行显示。

备注:

需要再项目manifest.json中,mp-weixin节点配置requiredPrivateInfos和permission。

在调用 uni.getFuzzyLocation 之前,确保请求用户授权获取位置信息,否则你会遇到如下提示:

微信开发者工具自带的getLocation就可以实现上述效果,但是申请没有getFuzzyLocation好申请,腾讯地图API中也可以根据当前IP地址来进行调用。

相关推荐
丁总学Java11 小时前
在微信小程序或前端开发中,picker 和 select 都是用户交互中用于选择的组件,但它们在功能、设计和使用场景上有一定的区别
微信小程序·小程序
刘登辉13 小时前
uniapp报毒
uni-app
星月昭铭13 小时前
uni-app打包成H5使用相对路径
uni-app·vue·html5
天草二十六_简村人16 小时前
kong搭建一套微信小程序的公司研发环境
java·后端·微信小程序·小程序·kong
没有天赋的搬砖者17 小时前
微信小程序实现根据不同的用户角色显示不同的tabbar并且可以完整的切换tabbar
微信小程序·小程序
低代码布道师18 小时前
智慧加油站小程序数据库设计文档
数据库·小程序
爱分享的淘金达人19 小时前
25年教师资格认定材料及认定详细流程‼
java·python·考研·小程序·tomcat
特严赤傲20 小时前
微信小程序获取用户地址
微信小程序
知码者21 小时前
虚拟健身教练小程序:AI动作识别与个性化训练计划生成
人工智能·微信小程序·小程序·小程序开发
un_fired1 天前
智能语音对话小程序功能优化day2-语音输入
小程序