跳转至

Vue2项目使用百度地图

JavaScript API GL 文档:https://lbsyun.baidu.com/index.php?title=jspopularGL/guide/helloworld

  1. 通过 script 引入百度外链

修改 index.html 模版文件,把外链引入,后面加上申请的 key

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
    <script src="https://api.map.baidu.com/api?type=webgl&v=2.0&ak=mEgbC3vGaaPnAxDeeHUollEZ"></script>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

通过在组件中也引入 script 外链解决报错问题,或者不加外链,通过 window 的方式访问地图对象

<template>
  <div>
    <div id="allmap"></div>
  </div>
</template>

<!-- <script src="https://api.map.baidu.com/api?type=webgl&v=2.0&ak=mEgbC3vGaaPnAxDeeHUollEZ"></script> -->
<script>
export default {
  name: 'test',
  data() {
    return {
      description: '项目信息'
    }
  },
  mounted(){
    // GL版命名空间为BMapGL
    var map = new window.BMapGL.Map("allmap");    // 创建Map实例
    map.centerAndZoom(new window.BMapGL.Point(118.5, 27.5), 5);  // 初始化地图,设置中心点坐标和地图级别
    map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
    map.setMapType(window.BMAP_EARTH_MAP);      // 设置地图类型为地球模式
  }
}
</script>
<style scoped>
#allmap {
  width: 100vw;
  height: 100vh;
}
</style>