vue项目使用高德地图的定位及关键字搜索功能

1.首先在index.html引入高德地图的秘钥。如图:
在这里插入图片描述注意:如果使用关键字搜索功能要加上 plugin=AMap.Autocomplete,AMap.PlaceSearch,否则功能无法使用,并会报错
2. 定位功能,代码如下:

const map = new AMap.Map(this.$refs.container, {
        resizeEnable: true
      }) // 创建Map实例
      const options = {
        'showButton': true, // 是否显示定位按钮
        'buttonPosition': 'LB', // 定位按钮的位置
        'buttonOffset': new AMap.Pixel(10, 20), // 定位按钮距离对应角落的距离
        'showMarker': true, // 是否显示定位点
        'showCircle': true, // 是否显示定位精度圈
        'circleOptions': {// 定位精度圈的样式
          'strokeColor': '#0093FF',
          'noSelect': true,
          'strokeOpacity': 0.5,
          'strokeWeight': 1,
          'fillColor': '#02B0FF',
          'fillOpacity': 0.25
        },
        zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点
      }
      AMap.plugin(['AMap.Geolocation'], function() {
        const geolocation = new AMap.Geolocation(options)
        map.addControl(geolocation)
        geolocation.getCurrentPosition()
      })
      //下面是点击地图时加入mark。注意:要在绑定事件前记录this,否则在绑定的回调方法中使用this将是该事件的this
      const _this = this
      AMap.event.addListener(map, 'click', function(e) {
        map.clearMap() // 清除地图上所有添加的覆盖物
        new AMap.Marker({
          position: e.lnglat,
          map: map
        })
        _this.handleMap(e.lnglat.getLng(), e.lnglat.getLat())
      })

3.关键字搜索功能
html部分代码(注意ref,id,class的名字要和官网保持一致,否则可能出不来想要的效果):

<template>
  <div class="map-chart">
    <div id="container" ref="container" />
    <div id="myPageTop">
      <table>
        <tr>
          <td>
            <label>请输入关键字:</label>
          </td>
        </tr>
        <tr>
          <td>
            <input id="tipinput">
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

script代码:

export default {
  name: 'Map',
  props: [],
  data() {
    return {
      placeSearch: null
    }
  },
  mounted() {
    this.mapInit()
  },
  methods: {
    mapInit() {
      const map = new AMap.Map(this.$refs.container, {
        resizeEnable: true
      }) // 创建Map实例
      const options = {
        'showButton': true, // 是否显示定位按钮
        'buttonPosition': 'LB', // 定位按钮的位置
        'buttonOffset': new AMap.Pixel(10, 20), // 定位按钮距离对应角落的距离
        'showMarker': true, // 是否显示定位点
        'showCircle': true, // 是否显示定位精度圈
        'circleOptions': {// 定位精度圈的样式
          'strokeColor': '#0093FF',
          'noSelect': true,
          'strokeOpacity': 0.5,
          'strokeWeight': 1,
          'fillColor': '#02B0FF',
          'fillOpacity': 0.25
        },
        zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点
      }
      //注意:要在绑定事件前记录this,否则在绑定的回调方法中使用this将是该事件的this
      const _this = this
      // 输入提示
      const autoOptions = {
        input: 'tipinput'
      }
      const auto = new AMap.Autocomplete(autoOptions)
      this.placeSearch = new AMap.PlaceSearch({
        map: map
      }) // 构造地点查询类
      AMap.event.addListener(auto, 'select', this.select)// 注册监听,当选中某条记录时会触发
      //点击搜索出的mark点事件
      AMap.event.addListener(this.placeSearch, 'markerClick', function(e) {
        _this.$emit('bMapDate', e.data.location.lng, e.data.location.lat)
      })
    },
    select(e) {
      this.placeSearch.setCity(e.poi.adcode)
      this.placeSearch.search(e.poi.name) // 关键字查询查询
    },
    handleMap(o, a) {
      this.$emit('bMapDate', o, a)
    }
  }
}
</script>

整体完成代码:

<template>
  <div class="map-chart">
    <div id="container" ref="container" />
    <div id="myPageTop">
      <table>
        <tr>
          <td>
            <label>请输入关键字:</label>
          </td>
        </tr>
        <tr>
          <td>
            <input id="tipinput">
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Map',
  props: [],
  data() {
    return {
      placeSearch: null
    }
  },
  mounted() {
    this.mapInit()
  },
  methods: {
    mapInit() {
      const map = new AMap.Map(this.$refs.container, {
        resizeEnable: true
      }) // 创建Map实例
      const options = {
        'showButton': true, // 是否显示定位按钮
        'buttonPosition': 'LB', // 定位按钮的位置
        'buttonOffset': new AMap.Pixel(10, 20), // 定位按钮距离对应角落的距离
        'showMarker': true, // 是否显示定位点
        'showCircle': true, // 是否显示定位精度圈
        'circleOptions': {// 定位精度圈的样式
          'strokeColor': '#0093FF',
          'noSelect': true,
          'strokeOpacity': 0.5,
          'strokeWeight': 1,
          'fillColor': '#02B0FF',
          'fillOpacity': 0.25
        },
        zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点
      }
      AMap.plugin(['AMap.Geolocation'], function() {
        const geolocation = new AMap.Geolocation(options)
        map.addControl(geolocation)
        geolocation.getCurrentPosition()
      })
      const _this = this
      AMap.event.addListener(map, 'click', function(e) {
        map.clearMap() // 清除地图上所有添加的覆盖物
        new AMap.Marker({
          position: e.lnglat,
          map: map
        })
        _this.handleMap(e.lnglat.getLng(), e.lnglat.getLat())
      })

      // 输入提示
      const autoOptions = {
        input: 'tipinput'
      }
      const auto = new AMap.Autocomplete(autoOptions)
      this.placeSearch = new AMap.PlaceSearch({
        map: map
      }) // 构造地点查询类
      AMap.event.addListener(auto, 'select', this.select)// 注册监听,当选中某条记录时会触发
      AMap.event.addListener(this.placeSearch, 'markerClick', function(e) {
        _this.$emit('bMapDate', e.data.location.lng, e.data.location.lat)
      })
    },
    select(e) {
      this.placeSearch.setCity(e.poi.adcode)
      this.placeSearch.search(e.poi.name) // 关键字查询查询
    },
    handleMap(o, a) {
      this.$emit('bMapDate', o, a)
    }
  }
}
</script>

<style scoped>
    .map-chart{
        position: relative;
        margin-bottom:15px;
        width: 100%;
        height: 400px;
        border: 1px #dddddd solid;
    }
    /deep/ .amap-logo,/deep/ .amap-copyright {
        display: none!important;
    }

    #container {
        margin-bottom:15px;
        width: 100%;
        height: 400px;
        border: 1px #dddddd solid;
        z-index: 99999999;
    }

    .button-group {
        position: absolute;
        bottom: 20px;
        right: 20px;
        font-size: 12px;
        padding: 10px;
    }

    .button-group .button {
        height: 28px;
        line-height: 28px;
        background-color: #0D9BF2;
        color: #FFF;
        border: 0;
        outline: none;
        padding-left: 5px;
        padding-right: 5px;
        border-radius: 3px;
        margin-bottom: 4px;
        cursor: pointer;
    }
    .button-group .inputtext {
        height: 26px;
        line-height: 26px;
        border: 1px;
        outline: none;
        padding-left: 5px;
        padding-right: 5px;
        border-radius: 3px;
        margin-bottom: 4px;
        cursor: pointer;
    }
    #tip {
        background-color: #fff;
        padding-left: 10px;
        padding-right: 10px;
        position: absolute;
        font-size: 12px;
        right: 10px;
        top: 20px;
        border-radius: 3px;
        border: 1px solid #ccc;
        line-height: 30px;
    }
    .amap-info-content {
        font-size: 12px;
    }
    #myPageTop {
        position: absolute;
        top: 5px;
        right: 10px;
        background: #fff none repeat scroll 0 0;
        border: 1px solid #ccc;
        margin: 10px auto;
        padding:6px;
        font-family: "Microsoft Yahei", "微软雅黑", "Pinghei";
        font-size: 14px;
        z-index: 99999999;
    }
    #myPageTop label {
        margin: 0 20px 0 0;
        color: #666666;
        font-weight: normal;
    }
    #myPageTop input {
        width: 170px;
    }
    #myPageTop .column2{
        padding-left: 25px;
    }
</style>

由于我在项目中使用了dialog,搜索出来的结果会在蒙版后面显示,去掉scope和加/deep/、>>>都没用,最后在index.html加样式。代码如下:

<style type="text/css">
    .amap-sug-result {
      z-index: 2999!important;
    }
  </style>

效果:
在这里插入图片描述

以上就是踩了无数坑总结出来的经验。。。

<think>好的,我需要帮助用户在Vue2项目中集成高德地图API,实现根据关键字搜索地理位置的功能。首先,我应该回顾用户提供的引用内容,看看有哪些已有的信息和可能的解决方案。 用户提供了三个引用,都是关于在Vue使用高德地图API的。引用[1]和[2]提到了输入提示插件和如何显示搜索结果,引用[3]则提到了使用lodash的debounce函数以及POI搜索。用户现在想要在Vue2中根据关键字搜索位置,可能需要结合这些信息。 首先,我需要确认高德地图API的基本使用步骤。根据官方文档,通常需要引入JS API,设置安全密钥,然后初始化地图和插件。Vue项目中可能需要使用AMapLoader来异步加载API,避免阻塞。 接下来,用户需要在输入框中输入关键字,然后触发搜索。这里可以考虑使用输入提示插件(AMap.AutoComplete)或者直接调用POI搜索接口。输入提示插件更适合实时显示建议,而POI搜索可能更适用于用户输入后执行搜索。根据引用[2],用户可能想要输入时显示提示,所以输入提示插件更适合。 但是用户的问题是根据关键字搜索位置,这可能涉及到执行搜索并显示结果,而不仅仅是输入提示。这时候可能需要结合两种方法:使用输入提示来获取建议,然后当用户选择某个建议时,获取其详细信息,或者直接使用POI搜索接口根据关键字获取结果。 根据引用[3],他们使用了AMapLoader和debounce函数,可能是为了减少API请求频率,避免频繁触发搜索。因此,在实现时,应该考虑对输入事件进行防抖处理。 现在需要构建一个示例步骤: 1. 注册高德开发者账号并创建应用,获取key和安全密钥。 2. 在Vue项目中安装必要的依赖,比如amap-jsapi-loader和lodash的debounce。 3. 在组件中引入AMapLoader,并初始化地图。 4. 创建输入框,绑定到Vue的数据属性。 5. 使用debounce处理输入事件,当输入变化时触发搜索。 6. 调用高德的POI搜索接口或输入提示插件来获取结果。 7. 处理返回的数据并展示,比如在地图上打点或显示列表。 需要注意,高德地图JS API需要在有安全密钥的情况下使用,且可能需要配置Web服务的API Key。此外,组件的销毁阶段需要清理地图实例,避免内存泄漏。 可能遇到的问题包括:跨域问题,但高德API应该处理好了;正确加载API库;输入事件处理是否正确;以及如何将搜索结果显示在地图上或列表中。引用[2]中提到的问题是关于多个输入框使用输入提示插件,但用户的问题可能只需要一个输入框,所以可以直接参考官方示例,但需要适配到Vue2的响应式数据绑定。 总结步骤,编写示例代码,并确保使用$和$$格式的数学公式(如果有的话),但在这个问题中可能不涉及数学公式。需要检查是否有任何地方需要行内或独立公式,比如在计算坐标时的数学表达式,但可能不需要。不过用户要求所有数学表达式必须正确使用LaTeX,所以如果有任何地方需要,比如计算距离的公式,应该用$...$包裹。 最后,生成相关问题,可能涉及性能优化、错误处理、多个输入框的实现等。</think>在Vue2项目中集成高德地图API实现关键字搜索功能,需按照以下步骤操作: --- ### 一、准备工作 1. **注册高德开发者账号** 前往[高德开放平台](https://lbs.amap.com/)注册账号,创建应用并获取`Web端JS API Key`和安全密钥`securityJsCode`[^1]。 2. **安装依赖** ```bash npm install @amap/amap-jsapi-loader --save npm install lodash --save # 用于输入防抖 ``` --- ### 二、基础实现代码 #### 1. 初始化地图与搜索功能 ```html <template> <div> <input v-model="keyword" @input="handleSearch" placeholder="输入地点关键字" > <div id="mapContainer" style="width: 600px; height: 400px"></div> <ul v-if="results.length"> <li v-for="item in results" :key="item.id" @click="selectLocation(item)"> {{ item.name }} - {{ item.address }} </li> </ul> </div> </template> <script> import AMapLoader from '@amap/amap-jsapi-loader'; import { debounce } from 'lodash'; export default { data() { return { map: null, keyword: '', results: [] }; }, mounted() { this.initMap(); }, methods: { async initMap() { try { const AMap = await AMapLoader.load({ key: 'YOUR_JS_API_KEY', // 替换为实际Key securityJsCode: 'YOUR_SECURITY_JS_CODE', // 安全密钥 plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch'] }); this.map = new AMap.Map('mapContainer', { zoom: 13, center: [116.397428, 39.90923] // 默认北京中心 }); } catch (error) { console.error('地图初始化失败:', error); } }, // 防抖处理搜索请求(300ms延迟) handleSearch: debounce(function() { if (!this.keyword.trim()) return; const AMap = window.AMap; const autoOptions = { city: '全国' }; const autoComplete = new AMap.AutoComplete(autoOptions); autoComplete.search(this.keyword, (status, result) => { if (status === 'complete' && result.tips) { this.results = result.tips.filter(item => item.location); } }); }, 300), // 选中地点并定位 selectLocation(item) { this.map.setCenter([item.location.lng, item.location.lat]); this.map.setZoom(15); } }, beforeDestroy() { if (this.map) this.map.destroy(); // 避免内存泄漏 } }; </script> ``` --- ### 三、关键配置说明 1. **安全密钥配置** 高德JS API v2.0需在`load`方法中添加`securityJsCode`参数,否则会触发`"AMap" is undefined`错误[^1]。 2. **输入防抖优化** 使用`lodash.debounce`控制输入频率,避免高频触发API请求[^3]。 3. **结果筛选逻辑** 通过`filter(item => item.location)`过滤掉无坐标数据,确保地图可定位。 --- ### 四、常见问题解决 - **跨域错误**:检查`securityJsCode`是否正确配置。 - **无法获取数据**:确认网络请求是否被浏览器插件拦截,或尝试使用`JSONP`模式。 - **多输入框场景**:参考引用[2]将功能封装为独立函数,通过`id`区分不同输入框。 ---
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值