vue3+ts+amap/amap-jsapi-loader实现高德地图搜索选取地点

博客介绍了在页面使用高德地图API的步骤,包括安装amap/amap-jsapi-loader、在高德开放平台注册并获取key,还说明了在页面构建容器、引入amap/amap-jsapi-loader、初始化地图的操作,最后提及完成搜索框配置及展示完整代码和效果图。

1.安装amap/amap-jsapi-loader

npm i amap-jsapi-loader --save

2.注册高德api

官网地址:高德开放平台 | 高德地图API (amap.com)

注册之后点击右上角控制台,在如下位置添加key

按下图操作生成属于你的key(后面要用)

 

 3.在页面使用

创建一个组件

1.页面构建

html页面如下,一个容器包裹一个输入框,分别赋予id,container是地图容器

<div id="container" style="width: 100%;height: 600px;position: relative">
      <input
          v-model="keyword"
          class="keyword"
          id="keyword"
          placeholder="请输入搜索位置"
          style="position: absolute;z-index: 99;"
      />
    </div>
  </div>

2.引入amap/amap-jsapi-loader

这里我直接在页面内引用

import AMapLoader from "@amap/amap-jsapi-loader";

3.初始化地图

import AMapLoader from "@amap/amap-jsapi-loader";
import { reactive, ref, shallowRef} from 'vue'

const keyword = ref('')
// 存储搜索用的数据
const form: any = reactive({
  address: '',
})
const ininMap = () => {
  AMapLoader.load({
    key: 'your key',//api服务key--另外需要在public中使用安全密钥!!!
    version: '1.4.4',// 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete']// 需要使用的的插件列表
  }).then((AMap) => {
        map = new AMap.Map('container', {
          resizeEnable: true,
          zoom: 9.5, // 地图显示的缩放级别
          center: [117.2, 31.8]//中心点
        })
    }
}

这里的key就是刚刚申请的key,填上即可

另外,还需在项目的public文件夹的index.html文件里添加安全密钥,代码如下

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
  <script>
      window._AMapSecurityConfig = {
          securityJsCode:'你的安全密钥',
      };//在这里添加
  </script>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

配置完成了接下来就是完成搜索框的配置

代码如下

const ininMap = () => {
  AMapLoader.load({
    key: 'your key',//api服务key--另外需要在public中使用安全密钥!!!
    version: '1.4.4',// 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete']// 需要使用的的插件列表
  })
      .then((AMap) => {
        map = new AMap.Map('container', {
          resizeEnable: true,
          zoom: 9.5, // 地图显示的缩放级别
          center: [117.2, 31.8]
        })
        AMap.plugin(
            ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Geocoder'],
            function (
callback: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null) {
              const autoOptions = {
                input: 'keyword' // 使用联想输入的input的id
              }
              const autocomplete = new AMap.Autocomplete(autoOptions)
              const placeSearch = new AMap.PlaceSearch({
                map: map
              })
              const geocoder = new AMap.Geocoder({
                radius: 1000,
                extensions: 'all'
              })
              AMap.event.addListener(autocomplete, 'select', function (e) {
                placeSearch.setCity(e.poi.adcode)
                placeSearch.search(e.poi.name, function (status, result) {
                  const pois = result.poiList.pois
                  for (let i = 0; i < pois.length; i++) {
                    if (pois[i].name === e.poi.name) {
                      console.log('搜索结果', pois[i])
                      geocoder.getAddress(
                          [pois[i].location.lng, pois[i].location.lat],
                          function (status, result) {
                            console.log(result)
                            if (status === 'complete' && result.info === 'OK') {
                              form.address = result.regeocode.formattedAddress
                            } else {
                              form.address = ''
                            }
                          }
                      )
                    }
                  }
                })
              })
            }
        )
      })
      .catch((e) => {})
}

页面完整代码如下

<template>
  <div class="box">
    <div id="container" style="width: 100%;height: 600px;position: relative">
      <input
          v-model="keyword"
          class="keyword"
          id="keyword"
          placeholder="请输入搜索位置"
          style="position: absolute;z-index: 99;"
      />
    </div>
  </div>
</template>


<script setup lang="ts">
import AMapLoader from "@amap/amap-jsapi-loader";
import { reactive, ref, shallowRef} from 'vue'

const keyword = ref('')
// 存储搜索用的数据
const form: any = reactive({
  address: '',
})
let map = shallowRef(null)
const ininMap = () => {
  AMapLoader.load({
    key: 'your key',//api服务key--另外需要在public中使用安全密钥!!!
    version: '1.4.4',// 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete']// 需要使用的的插件列表
  })
      .then((AMap) => {
        map = new AMap.Map('container', {
          resizeEnable: true,
          zoom: 9.5, // 地图显示的缩放级别
          center: [117.2, 31.8]
        })
        AMap.plugin(
            ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Geocoder'],
            function (callback: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null) {
              const autoOptions = {
                input: 'keyword' // 使用联想输入的input的id
              }
              const autocomplete = new AMap.Autocomplete(autoOptions)
              const placeSearch = new AMap.PlaceSearch({
                map: map
              })
              const geocoder = new AMap.Geocoder({
                radius: 1000,
                extensions: 'all'
              })
              AMap.event.addListener(autocomplete, 'select', function (e) {
                placeSearch.setCity(e.poi.adcode)
                placeSearch.search(e.poi.name, function (status, result) {
                  const pois = result.poiList.pois
                  for (let i = 0; i < pois.length; i++) {
                    if (pois[i].name === e.poi.name) {
                      console.log('搜索结果', pois[i])
                      geocoder.getAddress(
                          [pois[i].location.lng, pois[i].location.lat],
                          function (status, result) {
                            console.log(result)
                            if (status === 'complete' && result.info === 'OK') {
                              form.address = result.regeocode.formattedAddress
                            } else {
                              form.address = ''
                            }
                          }
                      )
                    }
                  }
                })
              })
            }
        )
      })
      .catch((e) => {})
}

ininMap()

</script>

 完成效果图

 

### 集成高德地图 JavaScript API 加载器到 Vue 3 和 TypeScript #### 安装依赖包 为了在 Vue 3 和 TypeScript 项目中集成高德地图,首先需要安装 `@amap/amap-jsapi-loader` 及其类型定义文件: ```bash npm install @amap/amap-jsapi-loader --save npm install @types/webpack-env --save-dev ``` 上述命令会下载必要的加载器以及 Webpack 的环境变量类型声明[^1]。 #### 创建地图初始化函数 创建一个新的工具模块用于处理地图API的初始化工作,在此过程中可以利用 TypeScript 提供更强健的类型安全特性。下面是一个简单的实现方式: ```typescript // src/utils/map.ts import AMapLoader from &#39;@amap/amap-jsapi-loader&#39;; export const initMapApi = async () => { try { await AMapLoader.load({ key: &#39;your_amap_api_key&#39;, // 替换成自己的key version: &#39;2.0&#39;, plugins: [] }); console.log(&#39;AMap loaded successfully&#39;); } catch (error) { console.error(&#39;Failed to load AMap:&#39;, error); } }; ``` 这段代码展示了如何通过 `@amap/amap-jsapi-loader` 来异步加载高德地图API,并设置相应的参数如版本号和插件列表等。 #### 组件内调用 为了让地图能够在页面上显示出来,还需要修改对应的 Vue 组件来确保地图API被正确加载并渲染至DOM节点之上。这里推荐将地图API的加载逻辑放在组件生命周期钩子之前执行,即 `beforeMount()` 方法里[^2]。 ```html <template> <div id="mapContainer" style="width:100%; height:500px;"></div> </template> <script lang="ts"> import { defineComponent, onBeforeMount } from &#39;vue&#39;; import { initMapApi } from &#39;@/utils/map&#39;; export default defineComponent({ name: &#39;MapView&#39;, setup() { onBeforeMount(async () => { await initMapApi(); /* 这里可以根据需求进一步操作 */ }); return {}; } }); </script> ``` 以上配置使得当组件即将挂载时触发地图API的加载过程,从而保证了地图实例可以在视图呈现前完成初始化。 #### 使用官方Vue组件库(可选) 如果希望更方便地管理地图及其交互行为,则可以选择使用由社区维护的 [@vuemap/vue-amap](https://vue-amap.guyixi.cn/) 库来进行开发[^3]。该库提供了丰富的功能接口和支持多种场景下的应用案例,能够极大地简化开发者的工作量。
评论 7
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EUEY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值