准备工作

  1. 在public中的index.html中初始化地图
<script src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>
  1. 在 .eslintrc.js 中配置AMap和AMapUI
globals: {
    "AMap": "true",
    "AMapUI":"true",
  }

实现思路

  1. 封装一个全局组件scottMap.vue,用于加载地图
  2. 封装一个基于scottMap.vue的组件mapVectorLine.vue,用于在地图上画出矢量图形
  3. 通过v-if和组件传参,确定需要的地图组件
  4. 组件嵌套封装代码(一个地图上面有多个功能),相比一个地图上封装一个功能,这种方式加载速度更快

scottMap.vue

<template>
  <div class="m-map">
    <div id="js-container" class="map">正在加载数据 ...</div>
    <div class="route">
        <map-vector-line v-if="isVectorLine" :map="map"></map-vector-line>
    </div>
  </div>
</template>

<script>
import MapVectorLine from './scottMap/mapVectorLine.vue'
/*
  传递参数:
    1. isVectorLine:  是否需要矢量路
*/
export default {
  name: 'mapIndex',
  components: { MapVectorLine },
  props: {
    isVectorLine: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      AMap: null,
      map: null
    }
  },
  mounted () {
    this.initMap()
  },
  methods: {
    // 实例化地图
    initMap () {
      this.AMap = window.AMap
      this.map = new AMap.Map('js-container', {
        zoom: 10, // 设置地图显示的缩放级别
        center: [117.27, 31.86] // 设置地图中心点坐标
      })
    }

  }

}
</script>

<style lang="css">
.m-map{ min-width: 500px; min-height: 300px; position: relative; }
.m-map .map{ width: 100%; height: 100%; }
.route{
    position: absolute;
    top: 10px;
    left: 200px;
    display: flex;
}
</style>

mapVectorLine.vue

<template>
    <div>
      <el-button @click="drawRoute">绘制路线</el-button>
      <el-button @click="closeRoute">关闭路线</el-button>
    </div>
</template>

<script>
export default {
  name: '',
  props: ['map'],
  components: {},
  data () {
    return {
      polyline: null,
      markerFlag: false // 判断是否有标点
    }
  },
  methods: {
    // 绘制矢量路线
    drawRoute () {
      var path = [
        [114.07869, 22.579645],
        [114.080128, 22.576],
        [114.082188, 22.576971],
        [114.082928, 22.579811]
      ]
      if (!this.markerFlag) {
        this.polyline = new AMap.Polyline({
          path: path,
          strokeColor: 'blue',
          strokeOpacity: 1,
          strokeWeight: 4,
          strokeStyle: 'dashed',
          lineJoin: 'round',
          lineCap: 'round'
        })
        this.map.add(this.polyline)
        // 缩放地图到合适的视野级别
        this.map.setFitView([this.polyline])
        this.markerFlag = true
      }
    },
    // 关闭矢量路线
    closeRoute () {
      if (this.polyline) {
        this.polyline.hide()
        this.markerFlag = false
      }
    }
  }
}
</script>

<style lang='less' scoped>

</style>

页面调用

 <scottMap class="scottMap"  :isVectorLine="true" ></scottMap>
Logo

前往低代码交流专区

更多推荐