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地址来进行调用。

相关推荐
码农客栈8 分钟前
小程序学习(十七)之获取前台分类数据并渲染
小程序
2601_949804929 分钟前
【全开源】AJAX家政上门服务系统小程序自营+多商家(高级授权)+独立端
小程序
h7ml14 分钟前
查券返利机器人图像识别:OpenCV 模板匹配对抗淘宝小程序动态化骨架屏
opencv·小程序·机器人
低代码布道师18 分钟前
教培管家第14讲:家长端——打造合规且顺畅的登录门户
低代码·小程序·云开发
说私域30 分钟前
私域流量生态重构:链动2+1模式S2B2C商城小程序的流量整合与价值创造
人工智能·小程序·流量运营·私域运营
说私域37 分钟前
AI智能名片S2B2C商城小程序赋能下线上向线下导流的机制与效果研究——基于线下专属优惠券的视角
人工智能·小程序·流量运营·私域运营
2501_915921431 小时前
不用 Xcode 上架 iOS,拆分流程多工具协作完成 iOS 应用的发布准备与提交流程
android·macos·ios·小程序·uni-app·iphone·xcode
CHU7290351 小时前
探索一番赏盲盒小程序:解锁多元互动体验新场景
小程序·php
2601_949804921 小时前
【全开源】西陆家政系统源码小程序(FastAdmin+ThinkPHP+原生微信小程序)
微信小程序·小程序
Greg_Zhong2 小时前
原生小程序中自定义三级联动(省市区)控件
小程序·微信小程序省市区接口联动