bing Map 初始化
通常地圖引入是<script></script>,但vue項目中僅某一兩個頁面需要用到百度地圖,所以不想在 index.html
中全局引用。
但是我直接在當前頁面通過 DOM 操作方式插入script標簽到當前document中,如下:
let scriptNode = document.createElement("script"); scriptNode.setAttribute("type", "text/javascript"); scriptNode.setAttribute("src", "http://www.bing.com/api/maps/mapcontrol?setLang=zh-CN&ak=您的密鑰"); document.body.appendChild(scriptNode);
結果會報“Mirosorft is not defined”的錯誤,這里的原因是由於異步加載,所以在調用"Mirosorft"的時候可能SDK並沒有引用成功。
那么:我采用了單獨創建initM
ap.js
腳本
// bing map init devTools export default { init: function (){ const lang ='ZH-ch' const bingKey = '密匙'; const BingMapUrl = 'http://www.bing.com/api/maps/mapcontrol?setLang='+ lang +'&key=' + bingKey; return new Promise((resolve, reject) => { if(typeof Microsoft !== "undefined") { resolve(Microsoft); return true; } // 插入script腳本 let scriptNode = document.createElement("script"); scriptNode.setAttribute("type", "text/javascript"); scriptNode.setAttribute("src", BingMapUrl); document.body.appendChild(scriptNode); // 等待頁面加載完畢回調 let timeout = 0; let interval = setInterval(() => { // 超時10秒加載失敗 if(timeout >= 20) { reject(); clearInterval(interval); } // 加載成功 if(typeof Microsoft !== "undefined") { resolve(Microsoft); clearInterval(interval); } timeout += 1; }, 100); }); } }
但是我說了,我做的項目是多語言的,而我的語種是存在session里的,這時需要在上面的方法里獲取到語種,如下:(保存、刪除、獲取我都寫出來了)
// 保存數據到sessionStorage sessionStorage.setItem('key', 'value'); // 從sessionStorage獲取數據 var data = sessionStorage.getItem('key'); // 從sessionStorage刪除保存的數據 sessionStorage.removeItem('key'); // 從sessionStorage刪除所有保存的數據 sessionStorage.clear();
我需要在vue頁面調用這個方法,於是我在mounted里面:
initBingMap.init()
.then((Microsoft) => { console.log(Microsoft) console.log("加載成功..."); this.loadMap(); })
剩下的地圖樣式就在loadMap方法里面寫了:
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), { /* No need to set credentials if already passed in URL */ center: new Microsoft.Maps.Location(47.624527, -122.355255), zoom: 8 }); Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () { var searchManager = new Microsoft.Maps.Search.SearchManager(map); var requestOptions = { bounds: map.getBounds(), where: 地址, callback: function (answer, userData) { map.setView({ bounds: answer.results[0].bestView }); map.entities.push(new Microsoft.Maps.Pushpin(answer.results[0].location)); } }; searchManager.geocode(requestOptions); });
當然:最重要的一點是要在頁面加入:
<div id='myMap' style='width: 100%; height: 300px;'></div>
這樣就成功了!