vue 高德地图实现输入框回车搜索地图

vue yekong 189℃

高德地图,需要实现输入框回车搜索地址效果。

vue 高德地图实现输入框回车搜索地图

搜索效果

引入PlaceSearch

key非真实,替换为自己的key就可以了。

    <script>
        window._AMapSecurityConfig = {
            securityJsCode: 'b50af813de4363ab7eb122ca0f48f811',
        }
    </script>
    <script
            type="text/javascript"
            src="https://webapi.amap.com/maps?v=1.4.15&key=8799ea91cf020faef54754fca59a2511&plugin=AMap.Geocoder,AMap.RangingTool,AMap.Heatmap,AMap.PlaceSearch"
    ></script>
    <script src="//webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script>

实例代码

<template>
  <div class="maps">
    <div class="placeSearch">
      <input type="text" placeholder="请输入地名" v-model="keyword" @keyup.enter="searchAndLocate">
    </div>
    <div ref="allmap" class="mapsMain"></div>
  </div>
</template>

<script>


export default {
  data() {
    return {
      map: null,
      placeSearch: '',
      keyword: ''
    }
  },

  mounted() {
    this.getGdMap()
  },

  methods: {

    // 高德地图相关
    getGdMap() {
      var that = this;
      that.map = new AMap.Map(this.$refs.allmap, {
        scrollWheel: true,
        viewMode: '2D',
        resizeEnable: true,
        zoom: 4,
        maxZoom: 30,
        minZoom: 0,
        center: [106.413099, 34.952327],
      });
      // 初始化地点搜索服务
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map
      });
    },
    searchAndLocate() {
      if (!this.keyword) {
        return;
      }
      // 使用AMap.PlaceSearch对象进行搜索
      this.placeSearch.search(this.keyword, (status, result) => {
        console.log(status, result)
        // 搜索成功
        if (status === 'complete' && result.info === 'OK') {
          // 将地图中心移动到搜索结果的第一个地点
          this.map.setCenter(result.poiList.pois[0].location);
        }
      });
    },
  }
}
</script>

要实现在Vue.js项目中使用高德地图的输入框搜索地名并回车定位的功能,你可以在methods中添加一个方法来处理输入框的回车事件,并使用高德地图的AMap.PlaceSearch服务进行搜索和定位。以下是实现这一功能的步骤和代码示例:

  1. 添加输入框监听事件:在<input>标签中添加@keyup.enter="searchAndLocate",这样当用户在输入框中按下回车键时,会调用searchAndLocate方法。

  2. 实现搜索和定位方法:在methods中添加searchAndLocate方法,使用AMap.PlaceSearch服务进行地点搜索,并将地图中心移动到搜索结果的第一个地点。

在上述代码中,searchAndLocate方法会在用户输入地名并按下回车键时被调用,它使用AMap.PlaceSearch服务进行搜索,并将地图中心移动到搜索结果的第一个地点。注意,this.placeSearchAMap.PlaceSearch的实例,它需要在getGdMap方法中初始化。

请确保你已经在项目中正确引入了高德地图的JavaScript SDK,并且在高德地图开放平台申请了API Key。

喜欢 (0)