Vue3 uses element-plus's Autodcomplete to access Baidu map address fuzzy search

First look at the renderings

insert image description here

accomplish

First of all, go to Baidu Maps to apply for ak officially, this step is skipped.

  1. main code
<div class="label">详细地址</div>
              <el-form-item prop="addressDetail">
                <el-autocomplete style="width: 100%" v-model="form.addressDetail" popper-class="autoAddressClass"
                  placeholder="请输入该详细地址" :fetch-suggestions="toSearch" :trigger-on-focus="false" clearable @select="handleSelect" @clear="clear"
                  >
                  <template v-slot="{ item }">
                    <i class="el-icon-search fl mgr10"></i>
                    <div style="overflow: hidden">
                      <span class="address ellipsis">{
    
    {
    
     item.address }}{
    
    {
    
     item.name }}</span>
                    </div>
                  </template>
                </el-autocomplete>
              </el-form-item>
  1. The toSearch method is very important. All the returned address information is displayed through the cb (an address array) inside. If you need latitude, longitude and other data information, you can obtain it through the handleSelect method. The baiduApiPoint method is mainly to call Baidu api , generate an address array based on the incoming path (city) and form.cityName (content in the input box).
// 返回的搜索内容事件处理
const toSearch = (str, cb) => {
    
    
  console.log(str)
  baiduApiPoint(str)
  cb(mapAddress.value)
}
// 选择地址触发事件
const handleSelect = (item) => {
    
    
  form.addressDetail = item.city + item.area + item.address + item.name // 详细地址
  form.longitude = item.location.lng // 经度
  form.latitude = item.location.lat // 纬度
}
// 清除
const clear = () => {
    
    
  form.addressDetail = '' // 详细地址
  form.longitude = '' // 经度
  form.latitude = '' // 纬度
}
const baiduApiPoint = (path) => {
    
    
  // 跨域调用百度api
  // 注意这里挂载在了window上
  window.callbackData = (data) => {
    
    
    if (data.results.length === 0) {
    
    
      console.log('请选择城市再输入详细地址!')
    }
    mapAddress.value = data.results
  }
  const url = `https://api.map.baidu.com/place/v2/search?query=${
      
      path}&region=${
      
      form.cityName}&page_size=20&output=json&ak=GwgzHwgqUGzFNZpRClR63mzn93RH0clK&callback=callbackData`
  const fetchJsonp = function (url) {
    
    
    const body = document.getElementsByTagName('body')[0]
    // 插入一个script
    const script = document.createElement('script')
    script.setAttribute('src', url)
    script.setAttribute('id', 'mapApi')
    body.appendChild(script)
  }
  fetchJsonp(url)
}

Guess you like

Origin blog.csdn.net/weixin_46319117/article/details/129624676
Recommended