前提是已经申请了自己的百度了哦!因为Vue3和百度不兼容问题所以接下来我们需要:
1.建立main.js同级文件 baiduMap.js
export function baiduMap(ak) {
return new Promise(function(resolve, reject) {
window.baiduMap = function() {
resolve()
}
var script = document.createElement('script')
script.type = 'text/javascript'
script.src = `http://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=baiduMap`
script.onerror = reject
document.head.appendChild(script)
})
}
2.第二步vue.config.js/vite.config.js引入
externals: { "BMap": "BMap" }
如果是Vue3的框架就在vue.config.js引入
如果是Vite+Vue3的框架,就在vite.config.js引入如图
3.接下来就可以直接渲染了
<template>
<div id="map"></div>
</template>
<style type="text/css">
#map {
width: 100%;
height: 500px;
}
</style>
<script>
import { baiduMap } from '../../../baiduMap.js'//咱们建立的baiduMap.js路径
export default {
data() {
return {
ak: '你的百度AK' // 百度密匙
}
},
mounted() {
// 动态引入较大类库避免影响页面展示
this.$nextTick(() => {
let _this = this;
baiduMap(_this.ak).then( thatMap => {
// 创建地图实例
var map = new BMap.Map("map");
// 创建地图实例
var point = new BMap.Point(116.404, 39.915);
// 创建点坐标
map.centerAndZoom(point, 15);
// 初始化地图,设置中心点坐标和地图级别
})
})
}
}
</script>