vue3+ts+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>

 完成效果图

 

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
很抱歉,我是AI语言模型,无法提供代码实现。不过,我可以给你提供一些参考和建议。 首先,你需要在Vue3中安装`amap-jsapi-loader`和`amap`。 ```bash npm install amap-jsapi-loader amap --save ``` 然后,在需要使用高德地图的组件中,引入`amap-jsapi-loader`和`amap`。 ```javascript import { AMapLoader } from 'amap-jsapi-loader'; import AMap from 'amap'; export default { name: 'MyMapComponent', data() { return { keyword: '', searchResult: null, map: null, marker: null, }; }, mounted() { AMapLoader.load({ key: 'your_amap_key', version: '2.0', plugins: ['AMap.Geocoder'], }).then((AMap) => { this.map = new AMap.Map('map-container', { zoom: 15, }); }); }, methods: { search() { if (!this.keyword) { return; } AMapLoader.load({ key: 'your_amap_key', version: '2.0', plugins: ['AMap.PlaceSearch'], }).then((AMap) => { const placeSearch = new AMap.PlaceSearch({ pageSize: 1, pageIndex: 1, city: '全国', }); placeSearch.search(this.keyword, (status, result) => { if (status === 'complete' && result.info === 'OK') { const poi = result.poiList.pois[0]; this.searchResult = poi.name + ', ' + poi.address; const lnglat = [poi.location.lng, poi.location.lat]; this.marker = new AMap.Marker({ position: lnglat, map: this.map, }); this.map.setCenter(lnglat); } else { this.searchResult = '无结果'; } }); }); }, }, }; ``` 在上面的代码中,我们使用了`AMapLoader`来异步加载高德地图API和插件。在`mounted`生命周期函数中,我们创建了一个地图实例,并将其挂载到DOM元素中。在`search`方法中,我们通过`AMap.PlaceSearch`来搜索关键词,并将第一个结果的位置和名称显示在地图上。 注意,在使用高德地图API之前,你需要先在高德地图开发者平台申请一个地图API的key,并在代码中替换`your_amap_key`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

EUEY

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

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

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

打赏作者

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

抵扣说明:

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

余额充值