高德地图动态绘制路线--轨迹巡航(vue)

1、将高德地图引入项目

第一步:在index.html文件中引入

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=自己申请的key"></script>
<script src="//webapi.amap.com/ui/1.0/main.js"></script>

第二步:在webpack.base.conf.js的module.exports里添加

externals: {
   'AMap': 'AMap'
 }

第三步:在使用高德地图的组件里使用

<template>
  ...
    <div id="container" class='container'> </div>
  ...
</template>
<script>
import AMap from 'AMap'
export default {
...
}
</script>

2、动态绘制路线

第一部分:创建组件实例

var emptyLineStyle = {
          lineWidth: 0,
          fillStyle: null,
          strokeStyle: null,
          borderStyle: null
 };
var pathSimplifierIns = new PathSimplifier({
        zIndex: 100,
        map: map, //所属的地图实例
        // clickToSelectPath: false,
        getPath: function(pathData, pathIndex) {
          //返回轨迹数据中的节点坐标信息,[AMap.LngLat, AMap.LngLat...] 或者 [[lng|number,lat|number],...]
          return pathData.path;
        },
        getHoverTitle: function(pathData, pathIndex, pointIndex) {
          //返回鼠标悬停时显示的信息
          if (pointIndex >= 0) {
              //鼠标悬停在某个轨迹节点上
              return pathData.name + ',点:' + pointIndex + '/' + pathData.path.length;
          }
          //鼠标悬停在节点之间的连线上
          return pathData.name + ',点数量' + pathData.path.length;
        },
        //仅展示驶过线
        renderOptions: {
            pathLineStyle: emptyLineStyle,
            pathLineSelectedStyle: emptyLineStyle,
            pathLineHoverStyle: emptyLineStyle,
            keyPointStyle: emptyLineStyle,
            startPointStyle: emptyLineStyle,
            endPointStyle: emptyLineStyle,
            keyPointHoverStyle: emptyLineStyle,
            keyPointOnSelectedPathLineStyle: emptyLineStyle,
            //轨迹线的样式(若想显示轨迹线就用下面这种)
            // pathLineStyle: {
            //     strokeStyle: 'blue',
            //     lineWidth: 4,
            //     dirArrowStyle: true
            // }
        }
        //若想显示轨迹线就用下面这种,二者选其一
       // renderOptions: {
            //轨迹线的样式
            // pathLineStyle: {
            //     strokeStyle: 'blue',
            //     lineWidth: 4,
            //     dirArrowStyle: true
            // }
       // }
  });

第二部分: 构建轨迹

pathSimplifierIns.setData([{
     name: '测试',
     path: [
        [119.405289, 41.904987],
        [117.964458, 40.54664],
        [118.47836, 41.135964],
        [118.949297, 41.670904]
     ]
 }]);

第三部分:创建一个巡航器

var navg0 = pathSimplifierIns.createPathNavigator(0, //关联第1条轨迹
          {
              loop: false, //循环播放
              speed: 100000,
              pathNavigatorStyle: {
                  autoRotate: true, //禁止调整方向
                  pathLinePassedStyle: null,
                  width: 24,
                  height: 24,
                  // content: PathSimplifier.Render.Canvas.getImageContent('../../static/blueSpot.png', onload, onerror),
                  strokeStyle: null,
                  fillStyle: null
              },
          });

navg0.start();

第四部分:加载PathSimplifier,启动页面(将第一到第三部分,在methods里封装成一个 initPage() 的方法,在 mounted() 里启动)

AMapUI.load(['ui/misc/PathSimplifier'], function(PathSimplifier) {
  if (!PathSimplifier.supportCanvas) {
        alert('当前环境不支持 Canvas!');
        return;
    }
   //启动页面
   that.initPage(PathSimplifier);
 });

完整代码如下(包含让地图实现高度自适应的方法):

<template>
  <div class="page_hello" :style="{ height: screenHeight + 'px' }">
    <div id="container" class='container'>
      
    </div>
  </div>
</template>
<script>
import AMap from 'AMap'
export default {
  name: 'Home',
  data () {
    return {
      screenHeight: document.documentElement.clientHeight
    }
  },
  mounted() {
    const that = this;
    window.onresize = () => {
      return (() => {
         window.screenHeight = document.documentElement.clientHeight
         that.screenHeight = window.screenHeight
      })()
    };
    //加载PathSimplifier,loadUI的路径参数为模块名中 'ui/' 之后的部分 
    AMapUI.load(['ui/misc/PathSimplifier'], function(PathSimplifier) {
        if (!PathSimplifier.supportCanvas) {
            alert('当前环境不支持 Canvas!');
            return;
        }
        console.log(PathSimplifier)
        //启动页面
        that.initPage(PathSimplifier);
    });
  },
  watch: {
    screenHeight (val) {
      // 为了避免频繁触发resize函数导致页面卡顿,使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变,就将其重新赋给data里的screenWidth
        this.screenHeight = val
        this.timer = true
        let that = this
        setTimeout(function () {
          // 打印screenWidth变化的值
          // console.log(that.screenHeight)
          that.timer = false
        }, 400)
      }
    }
  },
  methods: {
    // 在地图上动态画出某个路线
    initPage(PathSimplifier) {
      let map = new AMap.Map('container', {
        center: [143.308056,31.172531],
        resizeEnable: true,
        zoom: 4,
      });
      map.setMapStyle('amap://styles/4ba296aa426cbd000d79aac029d1ab94');
      var emptyLineStyle = {
          lineWidth: 0,
          fillStyle: null,
          strokeStyle: null,
          borderStyle: null
      };
      //创建组件实例
      var pathSimplifierIns = new PathSimplifier({
        zIndex: 100,
        map: map, //所属的地图实例
        // clickToSelectPath: false,
        getPath: function(pathData, pathIndex) {
          //返回轨迹数据中的节点坐标信息,[AMap.LngLat, AMap.LngLat...] 或者 [[lng|number,lat|number],...]
          return pathData.path;
        },
        getHoverTitle: function(pathData, pathIndex, pointIndex) {
          //返回鼠标悬停时显示的信息
          if (pointIndex >= 0) {
              //鼠标悬停在某个轨迹节点上
              return pathData.name + ',点:' + pointIndex + '/' + pathData.path.length;
          }
          //鼠标悬停在节点之间的连线上
          return pathData.name + ',点数量' + pathData.path.length;
        },
        renderOptions: {
          renderAllPointsIfNumberBelow: 6,
            pathLineStyle: emptyLineStyle,
            pathLineSelectedStyle: emptyLineStyle,
            pathLineHoverStyle: emptyLineStyle,
            keyPointStyle: emptyLineStyle,
            startPointStyle: emptyLineStyle,
            endPointStyle: emptyLineStyle,
            keyPointHoverStyle: emptyLineStyle,
            keyPointOnSelectedPathLineStyle: emptyLineStyle,
            //轨迹线的样式
            // pathLineStyle: {
            //     strokeStyle: 'blue',
            //     lineWidth: 4,
            //     dirArrowStyle: true
            // }
        }
      });

      //这里构建两条简单的轨迹,仅作示例
      pathSimplifierIns.setData([{
          name: '测试',
          path: [
              [119.405289, 41.904987],
              [117.964458, 40.54664],
              [118.47836, 41.135964],
              [118.949297, 41.670904]
          ]
      }]);
      //创建一个巡航器
      var navg0 = pathSimplifierIns.createPathNavigator(0, //关联第1条轨迹
          {
              loop: false, //循环播放
              speed: 100000,
              pathNavigatorStyle: {
                  autoRotate: true, //禁止调整方向
                  pathLinePassedStyle: null,
                  width: 24,
                  height: 24,
                  // content: PathSimplifier.Render.Canvas.getImageContent('../../static/blueSpot.png', onload, onerror),
                  strokeStyle: null,
                  fillStyle: null,
                  pathLinePassedStyle: {
                    lineWidth: 6,
                    strokeStyle: 'blue',
                    // dirArrowStyle: {
                    //     stepSpace: 15,
                    //     strokeStyle: 'red'
                    // }
                  }
              },
          });

      navg0.start();
    },
    // 动态修改样式,实现高度自适应
    changeFixed(clientHeight) {
        //动态修改样式
        // console.log(clientHeight);
        this.$refs.slidebar.style.height = clientHeight - 2  +  "px";
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang='scss'>
.page_hello {
  .container {
    height: 100%;
  }
}
</style>

结果如下:
在这里插入图片描述

官方文档: 官方文档入口

本人属于刚入行的小菜鸟,如有错误的地方,欢迎指正。

  • 5
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实时路线轨迹的实现需要结合高德地图的定位功能和绘制功能。 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异步机制,需要注意回调函数的执行时机。另外,在实际应用中,还需要结合后端接口获取历史路线轨迹数据,并将其加载到地图上。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值