简单一步,带你入手Nuxt3 + 高德地图2.0

1、项目初始化

使用官方脚手架创建基本项目 Installation · Get Started with Nuxt

swift 复制代码
npx nuxi@latest init <project-name>

2、安装高德地图依赖 @amap/amap-jsapi-loader@amap/amap-jsapi-types

  • @amap/amap-jsapi-loader 是API依赖包
  • @amap/amap-jsapi-types 是Type声明包
sql 复制代码
yarn add @amap/amap-jsapi-loader @amap/amap-jsapi-types

3、编写插件 plugins/amap.client.ts

typescript 复制代码
// plugins/amap.client.ts
// 引入 AMapLoader 依赖包
import AMapLoader from '@amap/amap-jsapi-loader';
export default defineNuxtPlugin(async (nuxtApp) => {
  // 安全密钥
  ;(window as any)._AMapSecurityConfig = {
    securityJsCode: "「你申请的安全密钥」",
    serviceHost: '「你配置的安全密钥代理地址」'
  }
  console.log('mounted.window', window._AMapSecurityConfig)
  return {
    provide: {
      _AMap: await AMapLoader.load({
        key: '<您申请的key值>',
        version: '2.0',
        plugins: [],
      })
    }
  }
})

4、展示地图app.vue

编写地图渲染架构,这里简单就直接全屏渲染

xml 复制代码
<template>
  <div class="h-full w-full" style="height: 100vh">
    <client-only>
      <div :id="amapId" class="h-full w-full"></div>
    </client-only>
  </div>
</template>
<script setup lang="ts">
import '@amap/amap-jsapi-types'
import { shallowRef } from '@vue/reactivity'
// 地图实例
const map = shallowRef()
const amapId = computed(() => {
  return `amap_${Date.now()}`
})
// 初始化
const initMap = async () => {
  await nextTick()
  // 地图初始化
  map.value = new AMap.Map(amapId.value, {
    zoom: 14,
    center: [108.366407, 22.8177], // 中心点
    mapStyle: 'amap://styles/macaron',
  })
}
// 挂载
onMounted(() => {
  if (process.client) {
    initMap()
  }
})
// 卸载
onUnmounted(() => {
  map.value?.destroy()
})
</script>

效果

5、API测试

在使用接口之前一定要 注意 ,新版本的需要搭配安全码使用:AMAP JS API 安全密钥使用

xml 复制代码
<script type="text/javascript">
  window._AMapSecurityConfig = {
    securityJsCode: "「你申请的安全密钥」", 
    serviceHost: "你的代理服务器域名或地址/_AMapService",
    // 例如 :serviceHost:'http://1.1.1.1:80/_AMapService'
  }
</script>

以上安全码为securityJsCodeserviceHost 二选一,但是我们现在已经使用插件来配置了不需要在单独配置了

5.1 浏览器精准定位

typescript 复制代码
/** 浏览器精准定位 **/
const loadGeolocation = () => {
  AMap.plugin('AMap.Geolocation', () => {
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,//是否使用高精度定位,默认:true
      timeout: 10000,          //超过10秒后停止定位,默认:5s
      position:'RB',    //定位按钮的停靠位置
      offset: [10, 20], //定位按钮与设置的停靠位置的偏移量,默认:[10, 20]
      zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
    })
    map.value!.addControl(geolocation);
    geolocation.getCurrentPosition((status: string, result: any) => {
      console.log('geolocation.getCurrentPosition', status, result)
    })
  })
}

5.2 周边查询

typescript 复制代码
AMap.plugin('AMap.PlaceSearch', function() {
    //构造地点查询类
    const placeSearch = new AMap.PlaceSearch({ 
        type: '', // 兴趣点类别
        pageSize: 5, // 单页显示结果条数
        pageIndex: 1, // 页码
        city: "010", // 兴趣点城市
        citylimit: false,  //是否强制限制在设置的城市内搜索
        map: map.value, // 展现结果的地图实例
        panel: "panel", // 结果列表将在此容器中进行展示。
        autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
    })

    var cpoint = [108.378, 22.8092] //中心点坐标
    placeSearch.searchNearBy('', cpoint, 10e3, (status: string, result: any) => {
      console.log('placeSearch.searchNearBy', status, result)
    })
})

6、常见问题

    1. Q: Uncaught (in promise) ReferenceError: AMap is not defined
      A: 没有初始化好,检查下插件是否正确引入
    1. Q: <AMap JSAPI> Error key!
      A: 填写Key值无效
    1. Q: 使用API接口响应错误 error INVALID_USER_SCODE
      A: 填写的安全码错误,请检查是否正确或者没填写
    1. Q: 500 请填写key
      A: 初始化Key值缺失
相关推荐
wxz99911 天前
nuxt2项目
javascript·nuxt.js
vortesnail2 个月前
Nuxt3 切换主题色且不闪屏该怎么做?
前端·vue.js·nuxt.js
陶然同学2 个月前
【学生管理系统】权限管理之角色管理
java·elementui·nuxt.js·学生管理系统
陶然同学2 个月前
【学生管理系统】权限管理之用户管理
java·nuxt.js·学生管理系统
陶然同学2 个月前
【学生管理系统】权限管理
java·nuxt.js·项目·学生管理系统
黑羽同学2 个月前
理解Nuxt——基于Nuxt SSG纯前端实现游戏官网(SEO)
vue.js·全栈·nuxt.js
程序员海军2 个月前
2024 Nuxt3 年度生态总结
前端·nuxt.js
Amd7943 个月前
Nuxt.js 应用中的 error 事件钩子
前端·nuxt.js·web应用·稳定性·用户体验·错误处理·钩子
Amd7943 个月前
Nuxt.js 应用中的 render:response 事件钩子
nuxt.js·事件·ssr·处理·钩子·修改·响应
Amd7943 个月前
Nuxt.js 应用中的 dev:ssr-logs 事件钩子
开发·监控·日志·nuxt.js·调试·ssr·钩子