uniapp H5端中使用高德API

本文介绍如何在uniapp项目中使用高德地图API,通过引入在线jsAPI并封装为Promise函数,实现地图功能的调用。文章详细说明了创建工具类、加载API及定位操作的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

高德的API有现成的SDK支撑安卓/IOS 但是没有专门的API支撑H5(或者说不用专门支撑)

当uniapp中调用高德API的时候就会遇到问题:

因为直接用引入外部js肯定不行了 (uniapp项目中压根就没有 html 页面,这也是我最无语的地方,为这事找了一两天的解决方法)

所以为了解决这个问题就必须引入在线jsAPI

下面就介绍步骤

1.引入在线jsAPI 专门新建个工具类,这样当需要调用地图的时候直接引用该方法就行

a.直接引用js肯定不行,所以采用回调函数的方式引入

b.因为高德的API是异步的,所以我们把他封装成Promise函数

1、封装工具函数

export default function MapLoader() {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      resolve(window.AMap);
    } else {
		var script = document.createElement('script');
		 script.type = "text/javascript";
		 script.async = true;
		script.src = "https://webapi.amap.com/maps?v=1.4.15&key= 这里是你在高德开发者平台申请的Key值&callback=initAMap";
		script.onerror = reject;
		  document.head.appendChild(script);
    }
    window.initAMap  = () => {
      resolve(window.AMap);
    };
   })
  }

注意:key值换成自己的哈
没有的可以自己去高德开发者平台申请一个,传送门:https://lbs.amap.com

2、引入工具函数
import AMap from "../../tools/utils.js"
3、加载API

高德开放平台文档:https://lbs.amap.com/api/javascript-api

data() {
			return {
				title:'hello',
				provider:'',
				map: null,
				zoom:13,
				resAmap:null,
				scrollH:500,
				scrollW:500,
				initLat:38.913423,//初始维度
				initLng:116.368904,//初始经度
				covers:[],
				LlayAroundGroupOpen:true,  //l网周边
			}
		},
onLoad() {
			this.initAMap()
		},
		methods: {
			async initAMap() {
				try {
					this.resAmap = await AMap();
					this.$nextTick(function() {
						// this.getBroewerLatLng();
						var map = new this.resAmap.Map('map', {
							center: [this.initLng, this.initLat],
							zoom: this.zoom
						});
						this.map = map;
						console.log(this.map)
						this.resAmap.plugin('AMap.Geolocation', () => {
							var geolocation = new this.resAmap.Geolocation({
								enableHighAccuracy: true, //是否使用高精度定位,默认:true
								timeout: 10000, //超过10秒后停止定位,默认:5s
								buttonPosition: 'RB', //定位按钮的停靠位置
								// buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
								zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点

							});
							map.addControl(geolocation);
							geolocation.getCurrentPosition(function(status, result) {
								if (status == 'complete') {
									onComplete(result)
								} else {
									onError(result)
								}
							});

						});
						
						//解析定位结果
						var then = this;

						function onComplete(data) {
							console.log(data) // 获取到的定位信息
							then.initLat = data.position.lat;
							then.initLng = data.position.lng;
						}

						function onError(data) {
							console.log(data) // 定位失败的信息
						}

					})
				} catch (e) {
					console.log(e)
				}

			}

		}

最重要的事情是一定要将调用方法放到$nextTick中,因为这样才能保证完全请求完成才调用(具体原因参见Vue)
意思是 在页面加载完之后,再执行 $nextTick 里面的方法;

如有写的不详细的地方,还请各位指出。

### 集成高德地图APIUniApp H5项目 #### 获取开发者Key 为了能够在应用中使用高德地图的服务,首先需要注册成为高德开放平台的开发者并创建相应的应用程序来获得专属的应用程序密钥(即`key`)。此过程对于确保安全性和追踪服务调用量至关重要[^2]。 #### 初始化配置 在开始之前,请确认已经在项目的根目录下的`manifest.json`文件里完成了必要的权限声明以及网络请求白名单设置。这一步骤是为了让应用能够顺利访问外部资源和服务接口。 #### 地图初始化与定位 利用`uni.getLocation()`函数可方便地取得用户的当前位置信息,包括经度(`longitude`)和纬度(`latitude`)坐标值。接着可以通过调用高德的地图JavaScript API中的相应方法完成地图实例化,并将中心点设为用户当前所在地[^3]。 ```javascript // 在页面加载完成后执行 onLoad() { let map; uni.getLocation({ type: 'gcj02', success: function (res) { var longitude = res.longitude; var latitude = res.latitude; // 创建地图对象 map = new AMap.Map('container', { zoom: 16, center: [longitude, latitude] }); // 添加标记 var marker = new AMap.Marker({ position: new AMap.LngLat(longitude, latitude), title: "您在这里" }); map.add(marker); } }); } ``` #### 实现逆地理编码功能 当想要根据给定的经纬度查询具体的地址描述时,则需要用到高德提供的逆地理编码服务。下面是一个简单的例子展示了如何发送HTTP GET请求到指定URL以获取格式化的地址字符串。 ```javascript getAddress() { const that = this; uni.request({ url: 'https://restapi.amap.com/v3/geocode/regeo', method: 'GET', data: { location: `${this.longitude},${this.latitude}`, key: 'your_amap_api_key_here' }, success(res) { if (res.statusCode === 200 && res.data.status === '1') { console.log("Formatted Address:", res.data.regeocode.formatted_address); that.addressInfo = res.data.regeocode.formatted_address || ''; } else { console.error("Failed to get address", res.errMsg); } } }) }, ``` 请注意替换上述代码片段中的`your_amap_api_key_here`为你自己申请得到的有效API Key。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值