vue 高德地图根据两个经纬度生成轨迹

vue yekong 232℃

vue项目开发中,需要实现一个功能,根据两个经纬度点坐标,生成轨迹路线。

vue 高德地图根据两个经纬度生成轨迹

使用 AMap.Driving 类来创建一个驾车路线规划对象。需要提供两个参数:起点和终点的经纬度。这两个参数应该是 AMap.LngLat 类型的实例。

调用 AMap.Driving 对象的 search 方法来搜索路线。这个方法会返回一个 Promise,可以在 Promise 的 then 方法中处理搜索结果。搜索结果包含了路线的详细信息,包括路线的长度和预计的驾驶时间。

引入高德地图

在高德地图中,我们需要用到AMap.Driving

  <script
            type="text/javascript"
            src="https://webapi.amap.com/maps?v=1.4.15&key=8799ea91cf020faef54754fca59a2552&plugin=AMap.Geocoder,AMap.RangingTool,AMap.Heatmap,AMap.DistrictSearch,AMap.service,AMap.Driving"
    ></script>

实现代码

<template>
  <div class="gdMap">
    <div class="gdMapBut" @click="drawRoute(start,end)">生成路线</div>
    <div class="container" ref="mapContainer" id="container"></div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      map: null,
      driving: null,
      start: [117.660641, 26.286404],
      end: [117.660641, 26.286404]
    }
  },
  mounted () {
    this.map = new AMap.Map(this.$refs.mapContainer, {
      zoom: 10,
      center: [116.397428, 39.90923]
    })
    this.initDriving()
  },
  beforeDestroy () {
    if (this.map) {
      this.map.destroy()
    }
  },
  methods: {
    initDriving () {
      this.driving = new AMap.Driving({
        map: this.map
      })
    },
    drawRoute (start, end) {
      this.driving.search(start, end, function (status, result) {
        console.log(result)
        if (status === 'complete') {
          console.log('绘制驾车路线完成')
          console.log('路线距离:' + result.routes[0].distance + '米');
          console.log('预计驾驶时间:' + result.routes[0].time + '秒');
        } else {
          console.log('获取驾车数据失败:' + result)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

.gdMap {
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: 0;

  .container {
    position: relative;
    width: 100%;
    height: 100%;
    z-index: 10;
  }

  .gdMapBut {
    position: fixed;
    width: 100px;
    height: 50px;
    background: red;
    z-index: 100;
    cursor: pointer;
  }
}
</style>

喜欢 (0)