简单一步,带你入手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值缺失
相关推荐
Amd7944 小时前
Nuxt.js 应用中的 link:prefetch 钩子详解
页面加载·nuxt.js·用户体验·钩子·vue 3·预取优化·link:prefetch
Amd79421 小时前
Nuxt.js 应用中的 app:suspense:resolve 钩子详解
组件状态·nuxt.js·异步渲染·钩子函数·异步数据·vue suspense·app:suspense:resolve
Amd7942 天前
Nuxt.js 应用中的 app:mounted 钩子详解
生命周期·nuxt.js·钩子函数·组件渲染·dom操作·vue应用·app:mounted
天涯学馆4 天前
Vue.js与Nuxt.js:动态路由与中间件
前端·vue.js·nuxt.js
Amd7945 天前
Nuxt.js 应用中的 app:redirected 钩子详解
认证·日志·nuxt.js·ssr·重定向·钩子·示例
Amd7945 天前
Nuxt.js 应用中的 app:rendered 钩子详解
生命周期·nuxt.js·服务器渲染·日志记录·性能监控·钩子函数·ssr优化
Amd7948 天前
深入理解 Nuxt.js 中的 app:data:refresh 钩子
前端开发·nuxt.js·钩子函数·代码示例·数据刷新·ui优化·动态更新
Amd7949 天前
深入理解 Nuxt.js 中的 app:error:cleared 钩子
生命周期·nuxt.js·错误处理·应用开发·钩子·用户反馈·状态恢复
程序员长夜9 天前
nuxtjs学习-路由
前端·nuxt.js
Amd79410 天前
深入理解 Nuxt.js 中的 app:error 钩子
前端框架·nuxt.js·用户体验·错误处理·应用开发·钩子函数·代码示例