基于webpack结构的vue项目 搭建百度地图 示例

  • Post author:
  • Post category:vue



场景和环境:web软件开发,JavaScript API v3.0


1.安装

NPM

$ npm install vue-baidu-map --save

2.配置webpack.base.conf.js

  //全局安装后,这里可以不加
  externals: {
    "BMap": "BMap"
  },

3.配置index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>vue_SeleCou</title>
    <!--vue-cli 安装全局bMap后,这里可以不加-->
    <script  type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=填写你的ak" ></script>
  </head>
  <link rel="stylesheet" type="text/css" href="/style/common.less">

  <body>
    <div id="app"></div>
    <!--生成的文件将自动注入 -->
  </body>
</html>

4.全局注册

main.js

import Vue from 'vue'
import BaiduMap from 'vue-baidu-map'

Vue.use(BaiduMap, {
  // ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key */
  ak: 'YOUR_APP_KEY'    //填写你的ak
})

5.新建一个vue文件

baiduMap.vue

<template>
<!--地图容器-->
    <baidu-map
      class="bm-view"
      :center="this.center"
      :zoom="this.zoom" @ready="handler"
      :scroll-wheel-zoom="true"
      :mapStyle="mapStyle">
    </baidu-map>
</template>
<style>
  .bm-view {
    width: 100%;
    height: 800px;
  }

</style>

<script>

  //引入map实例
  import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
  export default {
    //模板注册
    components: {
      BaiduMap
    },
    data () {
      return {
        //自定义主题样式
        mapStyle: {
          styleJson: [
            {
              "featureType": "all",
              "elementType": "geometry",
              "stylers": {
                "hue": "#007fff",
                "saturation": 89
              }
            },
            {
              "featureType": "water",
              "elementType": "all",
              "stylers": {
                "color": "#ffffff"
              }
            }
          ]
        },
        center: {lng: 0, lat: 0},
        zoom: 15
      }
    },

    methods: {
      handler ({BMap, map}) {
        console.log(BMap, map)
        this.center.lng = 116.404
        this.center.lat = 39.915
        this.zoom = 15
      }
    },

    //初始化(地图坐标和缩放参数,可有可无)
    mounted(){
      this.lng = 116.404
      this.lat = 39.915
      this.zoom = 15
    },

}
</script>

6.配置路由

router/index.js

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

//懒加载式引入
const baiduMap = r => require.ensure([], () => r(require('@/page/baiduMap.vue')), 'baiduMap');


const routes = [
//路径映射
  {
    path: '/baiduMap',
    component: baiduMap
  },



const router=new Router({
  mode:"history",  //去掉地址栏#
	routes,
	strict: process.env.NODE_ENV !== 'production',
})



export default router

7.访问



版权声明:本文为wcdunf原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。