要在 Vue 中使用高德地图进行输入搜索,你需要首先在你的项目中引入高德地图的 JavaScript API。你可以通过在index.html文件中添加以下代码来引入 API:

<script src='https://webapi.amap.com/maps?v=1.4.15&key=您的API密钥'></script>

然后,在你的 Vue 组件中,你可以使用mounted生命周期钩子函数来初始化地图,并添加搜索输入框。以下是一个简单的例子:

<template>
  <div>
    <input type='text' v-model='searchKeyword' placeholder='输入搜索关键字'>
    <div id='map' style='width: 100%; height: 400px;'></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: '',
      map: null,
      marker: null
    };
  },
  mounted() {
    // 初始化地图
    this.map = new AMap.Map('map', {
      center: [116.397428, 39.90923],
      zoom: 13
    });

    // 创建搜索框
    AMap.plugin('AMap.Autocomplete', () => {
      this.autocomplete = new AMap.Autocomplete({
        input: 'searchKeyword'
      });
    });

    // 监听搜索框输入
    this.$watch('searchKeyword', keyword => {
      if (keyword) {
        AMap.plugin('AMap.PlaceSearch', () => {
          const placeSearch = new AMap.PlaceSearch({
            map: this.map
          });
          placeSearch.search(keyword, (status, result) => {
            if (status === 'complete' && result.poiList && result.poiList.pois) {
              const poi = result.poiList.pois[0];
              this.map.setCenter(poi.location);
              if (this.marker) {
                this.marker.setMap(null);
              }
              this.marker = new AMap.Marker({
                position: poi.location,
                map: this.map
              });
            }
          });
        });
      }
    });
  }
};
</script>

在这个例子中,我们在mounted生命周期钩子函数中初始化了地图,并创建了一个搜索框。当搜索框的值发生变化时,我们使用AMap.PlaceSearch进行关键字搜索,并在地图上显示结果。如果搜索成功,我们会将地图中心设置为第一个搜索结果的位置,并在地图上添加一个标记。

请确保将您的API密钥替换为你自己的高德地图API密钥。

Vue 使用高德地图实现搜索功能:完整指南

原文地址: https://www.cveoy.top/t/topic/qqHl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录