vue异步加载高德地图的实现(2)

<!--异步加载 高德地图JSAPI ,注意 callback 参数--> <script src="//webapi.amap.com/maps?v=1.3&key=您申请的key值&callback=my_init"></script> <!--引入UI组件库异步版本main-async.js(1.0版本) --> <script src="https://webapi.amap.com/ui/1.0/main-async.js"></script> <script type="text/javascript"> //JSAPI回调入口 function my_init() { initAMapUI(); //这里调用initAMapUI初始化 //其他逻辑 } </script>

关键是UI库依赖于地图js文件,在这里,我们可以js加载完的回调onload函数和promise.all()函数来实现。loadMap.js文件如下:

export function MP(key) { const p1 = new Promise(function (resolve, reject) { window.init = function () { console.log('script1-------onload'); resolve(AMap) }; let script = document.createElement("script"); script.type = "text/javascript"; script.src = "//webapi.amap.com/maps?v=1.4.6&key="+key+"&callback=init"; script.onerror = reject; document.head.appendChild(script); }); const p2 = new Promise(function (resolve,reject) { let script2 = document.createElement("script"); script2.type = "text/javascript"; script2.src = "https://webapi.amap.com/ui/1.0/main-async.js"; script2.onerror = reject; script2.onload = function(su){ console.log('script2-------onload',su); resolve('success') }; document.head.appendChild(script2); }); return Promise.all([p1,p2]) .then(function (result) { console.log('result----------->',result); return result[0] }).catch(e=>{ console.log(e);}) };

promise.all中的then的成功回调返回rusult是一个数组,分别代表p1和p2的结果,这里只返回p1的结果(map对象)就可以了。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/a00e1ce0e00ad42e3c6da83624b74793.html