vue使用高德地图实现订单历史轨迹

本来是想用vue-amap ,最后发现没有那样的可以参考的。于是转战高德原生地图。效果图在最后面。(一打开弹框,就能看到车子动态运行的轨迹,一个子就开始跑起来了)(本例子经过线上环境的检验,可直接复用)

一、引入高德地图

1.在index.html中引入高德地图

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

2.在vue.config.js 中或者 webpack.base.conf.js 中引入(不同的项目可能有不一样的文件)

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

二、上代码

 <el-table-column label="操作" align="center">
         
            <el-button type="success" @click="queryOrderTrack(scope.$index, scope.row)">查看历史轨迹</el-button>
          </template>
        </el-table-column>

 <!-- 轨迹弹出框, -->
    <el-dialog :visible.sync="trackVisible" title="订单轨迹" @close="closeBatteryHistroy" width="70%">
      <div id="map-container" style="width:100%; height:600px"></div>
    </el-dialog>

<script>
//import orderMap from "./OrderMap";
//引入高德地图
import AMap from "AMap";
export default {
  name: "orderList",
  //components: { orderMap },
  data() {
    return {
      listLoading: true,
      dialogVisible: false, //电池轨迹dialog
      //地图
      map: null,
      marker: null,
      polyline: null,
      passedPolyline: null,
      selectedDate: [],
      markerArr: [], //电池经纬度,也用于画线
      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: {
   
    //点击查看历史轨迹
    queryOrderTrack(index, row) {
      let that = this;
      that.trackVisible = true;
      that.$nextTick(() => {
        //初始化地图
        that.initMap();
      });

      that.listLoading = true;
      //接口获得数据后转换,高德接受的数据格式为[[115.823166,28.696888],[经度,纬度]]
      setTimeout(() => {
        that.listLoading = false;
        var orderId = row.id;
        this.$post("后端接口路径", {
          orderId: orderId
        })
          .then(result => {
            if (result.data.code === 0) {
              let data = result.data.data;
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  let tempArr = [];
                  tempArr.push(data[i].lng);
                  tempArr.push(data[i].lat);

                  //格式转换后push进订单经纬度
                  that.markerArr.push(tempArr);
                }
                that.$nextTick(() => {
                  //画线
                  that.playLine();
                });
              }
            } else {
              that.$message.warning(result.data.msg);
            }
          })
          .catch(error => {
            that.$message.error(error.message);
          });
      }, 1000);
    },

    //初始化地图
    initMap() {
      let that = this;
      that.map = new AMap.Map("map-container", {
        resizeEnable: true,
        zoom: 7
        // center: [120.6641561, 31.3063851] //地图中心点  使用下面的浏览器精确定位,注释这个中心点的初始化
      });
      AMap.plugin(["AMap.ToolBar"], function() {
        //加载工具条
        var tool = new AMap.ToolBar();
        that.map.addControl(tool);
      });

      //浏览器精确定位-定位点自定义  使用这个定位,就不需要上面的初始化地图时的 center
      let options = {
        showButton: true, //是否显示定位按钮
        buttonPosition: "LB", //定位按钮的位置
        /* LT LB RT RB */
        buttonOffset: new AMap.Pixel(10, 20), //定位按钮距离对应角落的距离
        showMarker: true, //是否显示定位点
        markerOptions: {
          //自定义定位点样式,同Marker的Options
          offset: new AMap.Pixel(-18, -36),
          content:
            '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>'
        }
      };

      AMap.plugin(["AMap.Geolocation"], function() {
        var geolocation = new AMap.Geolocation(options);
        that.map.addControl(geolocation);
        geolocation.getCurrentPosition();
      });
    },

    //画线
    playLine() {
      let that = this;
      //初始化起点终点
      that.initStartEnd();
      that.marker = new AMap.Marker({
        map: that.map,
        //小车出初始位置
        position: that.markerArr[0],
        icon: "https://webapi.amap.com/images/car.png",
        offset: new AMap.Pixel(-26, -13),
        autoRotation: true,
        angle: -90
      });
      // 绘制轨迹
      that.polyline = new AMap.Polyline({
        map: that.map,
        path: that.markerArr,
        showDir: true,
        strokeColor: "#28F", //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6 //线宽
        // strokeStyle: "solid"  //线样式
      });
      //小车移动的轨迹线
      that.passedPolyline = new AMap.Polyline({
        map: that.map,
        // path: that.markerArr,
        strokeColor: "#AF5", //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6 //线宽
        // strokeStyle: "solid"  //线样式
      });
      //marker移动时把经纬度传给小车移动的轨迹线
      that.marker.on("moving", function(e) {
        //设置组成该折线的节点数组
        that.passedPolyline.setPath(e.passedPath);
      });
      // marker开始移动
      that.marker.moveAlong(that.markerArr, 200);
      //自适应放大
      setTimeout(() => {
        that.map.setFitView();
      }, 500);
    },
    //初始化起点终点
    initStartEnd() {
      let that = this;
      //将icon添加进marker
      let startMarker = new AMap.Marker({
        position: new AMap.LngLat(that.markerArr[0][0], that.markerArr[0][1]),
        icon: that.startIcon,
        offset: new AMap.Pixel(-13, -30)
      });
      //将icon添加进marker
      let endMarker = new AMap.Marker({
        position: new AMap.LngLat(
          that.markerArr.pop()[0],
          that.markerArr.pop()[1]
        ),
        icon: that.endIcon,
        offset: new AMap.Pixel(-13, -30)
      });

      // 将 markers 添加到地图
      that.map.add([startMarker, endMarker]);
    },
    //关闭弹窗时
    closeBatteryHistroy() {
      this.selectedDate = [];
      this.markerArr = []; //订单司机位置经纬度,也用于画线
    },

    

  }
};
</script>


<style scoped>

</style>

官方实例参考:

https://lbs.amap.com/api/javascript-api/example/marker/replaying-historical-running-data/?sug_index=6

三、效果图

  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
实时路线轨迹实现需要结合高德地图的定位功能和绘制功能。 1. 首先,在Vue中引入高德地图的JavaScript API,并创建地图对象: ```javascript import AMapLoader from '@amap/amap-jsapi-loader' // 创建地图对象 let map = null AMapLoader.load({ key: 'your amap key', version: '2.0', plugins: ['AMap.Geolocation'] }).then((AMap) => { map = new AMap.Map('map-container') }) ``` 2. 调用高德地图的定位功能获取当前位置: ```javascript let geolocation = null // 创建定位对象 AMapLoader.load({ key: 'your amap key', version: '2.0', plugins: ['AMap.Geolocation'] }).then((AMap) => { geolocation = new AMap.Geolocation({ enableHighAccuracy: true, // 是否使用高精度定位,默认为false timeout: 10000, // 超过10秒后停止定位,默认为无穷大 buttonOffset: new AMap.Pixel(10, 20), // 定位按钮的位置偏移量 }) map.addControl(geolocation) // 获取当前位置 geolocation.getCurrentPosition((status, result) => { if (status === 'complete') { // 定位成功,将地图中心设置为当前位置 map.setCenter(result.position) } else { // 定位失败 console.log('定位失败', result.message) } }) }) ``` 3. 在地图上绘制路线轨迹: ```javascript let path = [] // 路线轨迹点集合 // 添加路线轨迹 let polyline = new AMap.Polyline({ path, strokeColor: '#00a1fe', strokeWeight: 5, }) polyline.setMap(map) // 更新路线轨迹 function updatePath(newPoint) { path.push(newPoint) polyline.setPath(path) } ``` 4. 实时更新路线轨迹: ```javascript // 开启定时器,每隔1秒更新路线轨迹 setInterval(() => { // 获取当前位置 geolocation.getCurrentPosition((status, result) => { if (status === 'complete') { // 定位成功,更新路线轨迹 updatePath(result.position) } else { // 定位失败 console.log('定位失败', result.message) } }) }, 1000) ``` 以上就是Vue高德地图实现实时路线轨迹的基本流程,需要注意的是,高德地图的JavaScript API使用了Promise异步机制,需要注意回调函数的执行时机。另外,在实际应用中,还需要结合后端接口获取历史路线轨迹数据,并将其加载到地图上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值