在 utils 里面新建 getLocation.js 封装获取经纬度的公用方法(优化加载速度动态 cdn 引入高德地图) 由于高德 Api 方法获取当前经纬度比较慢,如果需求是在获取到当前经纬度数据之后请求一些数据,需要搭配 promise 使用保证获取到经纬度信息。具体见下面代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 function loadSDK ( ) { if (window .AMap ) return ; return new Promise ((resolve, reject ) => { const script = document .createElement ("script" ); script.src = "http://webapi.amap.com/maps?v=1.4.6&key=*****************" ; document .head .appendChild (script); script.onload = resolve; script.onerror = reject; }); } export default async () => { await loadSDK (); return new Promise ((resolve ) => { AMap .plugin ("AMap.Geolocation" , () => { const geolocation = new AMap .Geolocation ({ enableHighAccuracy : false }); geolocation.getCurrentPosition ((status, result ) => { const res = status === "complete" ? result.position : { lat : 39.909187 , lng : 116.397451 }; console .log ("定位结果" , res); resolve (res); }); }); }); };
在 vue 页面中的使用(这里假设需求是请求离我最近店铺信息列表)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 <template> <div class ="main-container" > <div class ="list" > <div class ="list-item" v-for ="(item,index) in list" :key ="index" > //you can do something </div > </div > </div > </template> <script > import * as Api from '@/api/xxx.js' import getLocation from '@/utils/getLocation' export default { data ( ) { return { params : {}, list : [] } }, mounted ( ) { this .fetchList () }, methods : { async getPosition ( ) { const { lng, lat } = await getLocation () this .params = { lng, lat } }, async fetchList ( ) { await this .getPosition () const { list } = await Api .fetchList (this .params ) this .list = list } } } </script > <style lang ='less' scoped > </style >
注意如果在 index.html 中引入高德地图在全局使用 AMap 构造函数需要在 vue.config.js 添加如下配置,否则会报‘AMap is not defined’错误
1 2 3 4 5 6 7 module .exports = { configureWebpack : { externals : { AMap : "AMap" , }, }, };
在页面中使用(举个 🌰,代码未测试)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <script> import AMap from 'AMap' export default { methods :{ fn ( ){ AMap .plugin ('AMap.Geolocation' , () => { const geolocation = new AMap .Geolocation ({ enableHighAccuracy : false }) geolocation.getCurrentPosition ((status, result ) => { const res = status === 'complete' ? result.position : { lat : 39.909187 , lng : 116.397451 } console .log ('定位结果' , res) }) }) } } } </script>