当前位置:首页 > VUE

vue实现地图导航

2026-01-23 08:29:17VUE

使用高德地图API实现Vue地图导航

安装高德地图JavaScript API的Vue封装库

npm install @amap/amap-jsapi-loader --save

在Vue组件中引入并初始化地图

vue实现地图导航

import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  data() {
    return {
      map: null,
      AMap: null
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMap() {
      AMapLoader.load({
        key: '您的高德地图Key',  // 替换为实际key
        version: '2.0',
        plugins: ['AMap.Driving']
      }).then((AMap) => {
        this.AMap = AMap
        this.map = new AMap.Map('map-container', {
          viewMode: '2D',
          zoom: 13,
          center: [116.397428, 39.90923]  // 默认北京中心点
        })
      })
    }
  }
}

添加路线规划功能

在组件中添加导航方法

methods: {
  drawRoute(start, end) {
    const driving = new this.AMap.Driving({
      map: this.map,
      policy: this.AMap.DrivingPolicy.LEAST_TIME
    })

    driving.search([
      { keyword: start, city: '城市名' },
      { keyword: end, city: '城市名' }
    ], (status, result) => {
      if (status === 'complete') {
        console.log('路线规划完成')
      } else {
        console.error('路线规划失败', result)
      }
    })
  }
}

添加地图标记和信息窗口

实现地点标记和信息展示

vue实现地图导航

addMarker(position, title) {
  const marker = new this.AMap.Marker({
    position: position,
    title: title,
    map: this.map
  })

  const infoWindow = new this.AMap.InfoWindow({
    content: `<div>${title}</div>`
  })

  marker.on('click', () => {
    infoWindow.open(this.map, marker.getPosition())
  })
}

集成位置搜索功能

添加地点搜索方法

searchPlace(keyword) {
  const placeSearch = new this.AMap.PlaceSearch({
    map: this.map,
    city: '城市名'
  })

  placeSearch.search(keyword, (status, result) => {
    if (status === 'complete') {
      result.poiList.pois.forEach(poi => {
        this.addMarker([poi.location.lng, poi.location.lat], poi.name)
      })
    }
  })
}

响应式地图容器样式

确保地图容器正确显示

<template>
  <div id="map-container" style="width: 100%; height: 500px;"></div>
</template>

注意事项

  1. 需要在项目中引入高德地图的安全密钥
  2. 使用前需在高德开放平台申请Web端Key
  3. 实际部署时需要考虑跨域问题和https协议要求
  4. 移动端需额外处理触摸事件和响应式布局

标签: 地图vue
分享给朋友:

相关文章

vue按钮实现截屏

vue按钮实现截屏

Vue 按钮实现截屏的方法 在 Vue 项目中实现截屏功能可以通过多种方式完成,以下是几种常见的方法: 使用 html2canvas 库 安装 html2canvas 库: npm install…

vue实现菜单栏锚点

vue实现菜单栏锚点

实现锚点菜单的基本思路 在Vue中实现菜单栏锚点功能,主要涉及两个方面:创建可跳转的锚点位置,以及菜单项的点击滚动控制。通过监听滚动事件可以高亮当前可见区域的对应菜单项。 创建页面锚点位置 在需要跳…

vue 实现复选

vue 实现复选

Vue 实现复选功能 在 Vue 中实现复选功能可以通过多种方式完成,以下是常见的几种方法: 使用 v-model 绑定数组 通过 v-model 绑定一个数组,可以自动收集用户选择的复选框值。…

vue 实现权限

vue 实现权限

Vue 实现权限控制的方法 在 Vue 项目中实现权限控制通常涉及前端路由、组件和按钮级别的权限管理。以下是几种常见的实现方式: 路由权限控制 通过路由守卫实现权限验证,过滤用户无权访问的路由:…

vue实现长按

vue实现长按

Vue 实现长按功能的方法 在 Vue 中实现长按功能可以通过原生事件监听或自定义指令完成。以下是几种常见实现方式: 使用原生事件监听 通过 @mousedown 和 @mouseup 或 @tou…

vue 组件实现

vue 组件实现

Vue 组件实现方法 单文件组件 (SFC) 使用 .vue 文件格式,包含模板、脚本和样式三部分: <template> <div class="example">{{…