uniapp H5端中使用高德API

高德的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 里面的方法;

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

你可能感兴趣的:(uni-app)