使用vue+原生高德地图API+element-ui绘制后端返回的经纬度轨迹和定位

1,820 阅读1分钟

在公司想要做这个需求之前,我翻阅过很多资料,最终在高德地图原生API和vue-amap上还是选择了高德地图原生API,至于原因嘛,当然是因为官网有相关实例可参考,并且vue-amap还是要熟悉原生高德地图API,所以不如直接用高德地图原生API。在这段时间里也是绕过一段远路,最终完美完成了所达到的效果,话不多说,分享一下自己踏过的坑,也希望有大佬给指点一二。 ##一、引入高德地图

1、在项目入口文件index.html引入高德地图

       //引入高德地图
       <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=你的高德key"></script>

2、在vue.config.js中引入(若项目vue-cli版本低于3.0则在webpack.base.conf.js中引入,不同的项目可能有不一样的文件)

 module.exports = {
      configureWebpack: {
        externals: {
          'AMap': 'AMap' // 高德地图配置
          }
      }
}

二、相关代码

<template>
  <div class="app-container">
    ...
    <div id="carMap" style="width:100%;height:100%" />
  </div>
</template>
<script>
import AMap from 'AMap'
import InventoryManageAPI from '@/api/inventory-manage'
import { getMapTrack } from '@/api/sales-manage'//获取数据的接口
export default {
  name: 'SeeCar',
  data() {
    return {
      filterCondition: {
        keyCode: '',
        organId: '',
        groupId: ''
      },
      map: null, // 地图容器
      content: [], // 信息窗体内容
      cusContent: [],//客户信息窗体内容
      marker: null, // 标记
      marker1: null,
      marker2: null,
      markers: [],
      markerArr: [],
      tempArr: [],
      polyline: null,
      passedPolyline: null,
      startMarker: null,//起点标记
      endMarker: null,终点标记
      startIcon: new AMap.Icon({
        // 起点图标
        // 图标尺寸
        size: new AMap.Size(25, 34),
        // 图标的取图地址
        image:
          '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
        // 图标所用图片大小
        imageSize: new AMap.Size(135, 40),
        // 图标取图偏移量
        imageOffset: new AMap.Pixel(-9, -3)
      }),
      endIcon: new AMap.Icon({
        // 终点图标
        size: new AMap.Size(25, 34),
        image:
          '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
        imageSize: new AMap.Size(135, 40),
        imageOffset: new AMap.Pixel(-95, -3)
      })
    }
  },
  methods: {
    //初始化地图
    creatMap() {
      this.map = new AMap.Map('carMap', {
        resizeEnable: true, // 是否监听地图容器尺寸变化
        zoom: 11, // 级别
        center: [116.397428, 39.90923], // 中心点坐标
        viewMode: '3D'
      })
//调用接口获取经纬度相关信息
      InventoryManageAPI.getListWithBody('getDeliveryPathByCarCode', this.filterCondition).then(res => {
        this.content = []
        for (const l of res.data.pageItems) {
          this.content = [...this.content, { con: `车主:${l.ownerName} </br>车牌:${l.licenceCode}</br>编号:${l.carCode}</br>手机号:${l.ownerTel}</br>状态:${l.status}`, color: l.status === '已送货' ? '#67C23A' : '#E6A23C', lnglat: [l.longitude, l.latitude], id: l.carCode }]
        }
        this.content.forEach(con => {
          this.marker = new AMap.Marker({
            position: con.lnglat,
            icon: require('../../../../assets/image/car.png'),
            map: this.map,
            visible: true,
            id: con.id
          })
          this.marker.setLabel({
            offset: new AMap.Pixel(-90, -60), // 设置文本标注偏移量
            content: `<div style="background:${con.color};color:#fff;">${con.con}</div>`, // 设置文本标注内容 ,
            direction: 'right' // 设置文本标注方位
          })
          this.marker.id = con.id
          this.marker.on('click', this.markerClick)
          this.markers.push(this.marker)
          this.map.setFitView()
        })
      })
    },
    markerClick(e) {
//移除上一次点击的轨迹和marker、图标
      this.$nextTick(() => {
        if (this.polyline) {
          this.map.remove(this.polyline)
          this.map.remove(this.marker1)
          this.map.remove(this.marker2)
          this.map.remove([this.startMarker, this.endMarker])
        }
      })
      this.markerArr = []
      const data = {
        organId: this.filterCondition.organId,
        groupId: this.filterCondition.groupId,
        carCode: e.target.id
      }
      getMapTrack(data).then(result => {
        const position = result.data.pageItems[0].cars[0].gps
        if (position.length > 0) {
          position.forEach(item => {
            this.tempArr = [item.longitude, item.latitude]
            // 格式转换后push进订单经纬度
            this.markerArr.push(this.tempArr)
          })
          this.$nextTick(() => {
            this.playLine()
          })
          const customer = result.data.pageItems[0].cars[0].cuss
          if (customer.length > 0) {
            for (const cus of customer) {
              this.cusContent = [...this.cusContent, { id: cus.cusCode, con: `客户:${cus.cusName}</br>货物方数:${cus.cusBulk}</br>编号:${cus.cusCode}</br>手机号:${cus.cusPhone}</br>状态:${cus.cusFinish ? '已送货' : '未送货'}`, color: cus.cusFinish ? '#67C23A' : '#F56C6C', lnglat: [cus.cusLongitude, cus.cusLatitude] }]
            }
            console.log(this.cusContent)
            this.cusContent.forEach(con => {
              this.marker2 = new AMap.Marker({
                position: con.lnglat,
                icon: require('../../../../assets/image/customer.png'),
                map: this.map,
                visible: true
              })
              this.marker2.setLabel({
                offset: new AMap.Pixel(-97, -65), // 设置文本标注偏移量
                content: `<div style="background:${con.color};color:#fff;">${con.con}</div>`, // 设置文本标注内容 ,
                direction: 'right' // 设置文本标注方位
              })
              this.markers.push(this.marker2)
              this.map.setFitView()
            })
          }
        }
      })
    },
    playLine() {
      // 初始化起点终点
      this.initStartEnd()
      this.marker1 = new AMap.Marker({
        map: this.map,
        // 小车初始位置
        position: this.markerArr[0],
        icon: require('../../../../assets/image/car.png'),
        offset: new AMap.Pixel(-26, -13),
        autoRotation: true,
        angle: -90
      })
      // 绘制轨迹
      this.polyline = new AMap.Polyline({
        map: this.map,
        path: this.markerArr,
        showDir: true,
        strokeColor: '#28F', // 线颜色
        strokeOpacity: 1, // 线透明度
        strokeWeight: 6, // 线宽
        strokeStyle: 'solid' // 线样式
      })
      // marker开始移动
      this.marker1.moveAlong(this.markerArr, 10000)// 第二个参数代表行驶速度
      // 自适应放大
      this.map.setFitView()
    },
//自定义图标
    initStartEnd() {
      // 将icon添加进marker
      this.startMarker = new AMap.Marker({
        position: new AMap.LngLat(this.markerArr[0][0], this.markerArr[0][1]),
        icon: this.startIcon,
        offset: new AMap.Pixel(-13, -30)
      })
      // 将icon添加进marker
      this.endMarker = new AMap.Marker({
        position: new AMap.LngLat(this.markerArr[this.markerArr.length - 1][0], this.markerArr[this.markerArr.length - 1][1]),
        icon: this.endIcon,
        offset: new AMap.Pixel(-13, -30)
      })

      // 将 markers 添加到地图
      this.map.add([this.startMarker, this.endMarker])
    }
  }
}
</script>

<style lang="scss" scoped>
  >>> .amap-marker-label{
    border-radius: 6px;
    position: absolute;
    padding: 0;
    border: none;
    font-size: 16px;
    line-height: 16px;
  }
  >>> .amap-marker-label::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -15px;
    border-width: 10px;
    border-style: solid;
    border-color:black transparent transparent transparent;
}
</style>

最终效果如图

carMap.png

carMap2.png

总结:使用高德地图完成两个需求后,感觉确实挺好玩的,还有着很多功能可以发掘,这之间也碰到了一些问题,比如信息窗体只能地图上只能显示一个,所以我就采用了文本标记的方法代替了信息窗体,另外建议使用这个信息窗体的内容或者文本标注内容时,最好把content抽离出来遍历,这样有利于后期维护。(另外这个轨迹是个动画,是模仿官网实例轨迹回放)