百度地图3.0 +vue-cli 中引入vue.config.js
1.新建loadBMap.js页面
export default function baiduMap() { return new Promise(function(resolve, reject) { if (typeof window.BMap !== 'undefined') { resolve(window.BMap) return true } window.baiduMap = function() { resolve(window.BMap) } const script = document.createElement('script') script.type = 'text/javascript' script.src = 'https://api.map.baidu.com/api?v=2.0&ak=' + 'wMSkK0cjYksSGWNVwB7h3S3nt9xARQqn' + '&callback=baiduMap' script.onerror = reject document.head.appendChild(script) }) }
2.配置vue.config.js
module.exports = { configureWebpack: { externals: { 'BMap': 'BMap', } } }
3.实例化
<template> <div class="map-area" :id="mapId"></div> </template> <script> import baiduMap from "./utils/loadBMap.js"; export default { data() { return { mapId: "BMap-" + parseInt(Date.now() + Math.random()), myMap: null, }; }, mounted() { this.initMap(); }, methods: { initMap() { baiduMap("ZymqHy1ADWcNL9PRhTfCs6AGxDDjXKkC") .then(() => { // 百度地图API功能 let map = new BMap.Map(this.mapId); // 创建Map实例 map.centerAndZoom(new BMap.Point(116.404, 39.915), 6); // 初始化地图,设置中心点坐标和地图级别 map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放 }) .catch((err) => { console.log("地图加载失败"); }); }, }, }; </script> <style> .map-area { width: 100%; height: 100vh; } </style>
4.样式
<style> .map-area { width: 100%; height: 100vh; } </style>