baiduMap.js
export function baiduMap(ak) {
return new Promise(function(resolve, reject) {
// 异步加载
var script = document.createElement('script')
script.type = 'text/javascript'
script.src = `http://api.map.baidu.com/api?v=2.0&ak=${ak}&callback=MapLoadSuccess`
script.onerror = reject
document.head.appendChild(script)
window.MapLoadSuccess = function() {
var link = document.createElement('link')
link.rel = 'stylesheet'
link.href = `http://api.map.baidu.com/library/SearchInfoWindow/1.5/src/SearchInfoWindow_min.css`
document.head.appendChild(link)
// BMap加载完成,开始加载libs
var script2 = document.createElement('script')
script2.type = 'text/javascript'
script2.src = `http://api.map.baidu.com/library/SearchInfoWindow/1.5/src/SearchInfoWindow_min.js`
script2.onload = function() {
resolve({BMap: window.BMap, BMapLib: window.BMapLib});
}
document.head.appendChild(script2)
}
})
}
map.vue
<template>
<div class="baidu" ref="mapRef" id="baidumap"></div>
</template>
<script>
import { baiduMap } from "@/utils/baiduMap.js";
export default ({
data(){
return{
ak: "", // 百度的地图密钥AK
lnglat:{
lng:"116.40396298757886",
lat:"39.91511908708907"
}
}
},
methods:{
initMap(){
var _this = this
baiduMap(_this.ak).then(({BMap,BMapLib}) =>{
console.log(window.BMapLib)
console.log(BMap)
let map = new BMap.Map("baidumap"); // 创建Map实例
var poi = new BMap.Point(_this.lnglat.lng, _this.lnglat.lat)
map.centerAndZoom(poi, 16);
map.enableScrollWheelZoom();
var content = '<div style="margin:0;line-height:20px;padding:2px;">' +
'<img src="../img/baidu.jpg" alt="" style="float:right;zoom:1;overflow:hidden;width:100px;height:100px;margin-left:3px;"/>' +
'<br/>电话:<br/>简介:。' +
'</div>';
//创建检索信息窗口对象
var searchInfoWindow = null;
searchInfoWindow = new BMapLib.SearchInfoWindow(map, content, {
title : "百度大厦", //标题
width : 290, //宽度
height : 105, //高度
panel : "panel", //检索结果面板
enableAutoPan : true, //自动平移
searchTypes :[
BMAPLIB_TAB_SEARCH, //周边检索
BMAPLIB_TAB_TO_HERE, //到这里去
BMAPLIB_TAB_FROM_HERE //从这里出发
]
});
var marker = new BMap.Marker(poi); //创建marker对象
marker.enableDragging(); //marker可拖拽
searchInfoWindow.open(marker);
map.addOverlay(marker); //在地图中添加marker
}).catch((err) => {
console.log(err)
})
},
},
mounted(){
this.initMap()
},
})
</script>
<style scoped lang="scss">
#baidumap{
width: 100%;
height: 400px;
}
:deep()
.BMap_cpyCtrl {
display: none!important;
}
</style>
结果: