vue | 在 Vue 3 项目中集成高德地图(AMap)

一、准备工作

1. 获取高德地图 Key

  • 登录 高德开放平台
  • 创建应用 → 获取 Web 端 JS API Key

二、安装依赖

bash 复制代码
npm install @amap/amap-jsapi-loader
# 或
yarn add @amap/amap-jsapi-loader

不要直接通过 <script> 引入 CDN,避免与 Vue 响应式冲突。


三、封装高德地图 Hook

创建 hooks/useAmap.js

javascript 复制代码
import { onMounted, onUnmounted, ref } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const useAmap = (containerId, options = {}) => {
  const map = ref(null)
  const AMap = ref(null)

  const initMap = async () => {
    try {
      // 加载高德地图 SDK
      const amap = await AMapLoader.load({
        key: '', // 替换为你的 key
        version: '2.0', // 推荐 2.0+
        plugins: [
          'AMap.Geolocation',
          'AMap.Marker',
          'AMap.InfoWindow',
          'AMap.Polyline',
          'AMap.Circle',
          'AMap.Scale',
          'AMap.ToolBar',
        ],
      })

      AMap.value = amap

      // 初始化地图
      const mapInstance = new amap.Map(containerId, {
        zoom: options.zoom || 16,
        center: options.center || [116.397428, 39.90923], // 默认北京
        viewMode: '3D',
        layers: [new amap.TileLayer.Satellite(), new amap.TileLayer.RoadNet()],
        visible: true,
        resizeEnable: true,
        zooms: [2, 20],
      })

      map.value = mapInstance

      // 可选:添加缩放控件等
      mapInstance.addControl(new amap.ToolBar())
      mapInstance.addControl(new amap.Scale())

      return mapInstance
    } catch (error) {
      console.error('高德地图加载失败:', error)
    }
  }

  onMounted(() => {
    initMap()
  })

  onUnmounted(() => {
    if (map.value) {
      map.value.destroy()
    }
  })

  return {
    map,
    AMap,
    initMap,
  }
}

export default useAmap

四、在组件中使用

javascript 复制代码
<template>
  <div id="amap-container" class="map-container"></div>
</template>

<script setup>
import { onMounted } from 'vue'
import useAmap from '@/hooks/useAmap'

const { map, AMap, initMap } = useAmap('amap-container', {
  zoom: 13,
  center: [84.920629, 45.417129],
})
onMounted(() => {
  initMap()
})
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 600px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>

五、实现效果

相关推荐
掘金安东尼5 小时前
纯 CSS 实现弹性文字效果
前端·css
牛奶6 小时前
Vue 基础理论 & API 使用
前端·vue.js·面试
牛奶6 小时前
Vue 底层原理 & 新特性
前端·vue.js·面试
anOnion6 小时前
构建无障碍组件之Radio group pattern
前端·html·交互设计
pe7er6 小时前
状态提升:前端开发中的状态管理的设计思想
前端·vue.js·react.js
SoaringHeart7 小时前
Flutter调试组件:打印任意组件尺寸位置信息 NRenderBox
前端·flutter
晚风予星8 小时前
Ant Design Token Lens 迎来了全面升级!支持在 .tsx 或 .ts 文件中直接使用 Design Token
前端·react.js·visual studio code
sunny_8 小时前
⚡️ vite-plugin-oxc:从 Babel 到 Oxc,我为 Vite 写了一个高性能编译插件
前端·webpack·架构
GIS之路8 小时前
ArcPy 开发环境搭建
前端
林小帅10 小时前
【笔记】OpenClaw 架构浅析
前端·agent