使用百度地图实现地址自动检索

633 阅读1分钟

前提条件:

首先将本地域名映射到外网,可以使用 NgrokNatapp 完成。

Ngrok

使用教程:www.ngrok.cc/_book/start…

隧道信息配置如下

image.png

完成本地域名映射到外网

image.png

Natapp

参考文章:blog.csdn.net/w405722907/…

隧道信息配置如下

image.png

完成本地域名映射到外网

image.png

地址检索百度api:

lbsyun.baidu.com/index.php

image.png 相关地址:lbsyun.baidu.com/index.php?t…

外接api访问地址

请求资源地址--http://api.map.baidu.com/place/v2/search?query=ATM机&tag=银行&region=北京&output=json&ak=您的ak//GET请求

获取服务密钥(ak)

image.png ak 配置如下:

image.png

前端接入element-ui的Autocomplete组件

element.eleme.cn/#/zh-CN/com… 组件图如下:

image.png

前端代码

main.js中加入:
1.import { Message,Autocomplete } from 'element-ui'
2.Vue.use(Autocomplete);

vue.config.js中加入:
module.exports = {
  devServer:{  
    disableHostCheck: true, // 让vue不强制要求使用host来访问
    host:'localhost',
    port:8081, 
    proxy:{
      '/api':{
        // target:'http://localhost:8081',
        // target:'http://yangguo.natapp1.cc',
       target:'http://localhost:8888',
        changeOrigin:true,
        pathRewrite:{
          '/api':''
        }
      },
      'baiduMapApi':{ 
        target:'http://api.map.baidu.com',
        changeOrigin:true, //允许跨域
        pathRewrite:{
          '/baiduMapApi':''
        }
      }
    }
  }
}

组件接入

<div class="item">
<!-- 1. 引入组件支持 -->
    <el-autocomplete
      class="inline-input"
      v-model="checkedItem.detailAddress"
      :fetch-suggestions="querySearch"
      placeholder="请输入详细地址"
      :trigger-on-focus="false"
      @select="handleSelect"
    ></el-autocomplete> 
</div>

代码逻辑

data() {
    return {
      checkedItem: {
        province: "",
        city: "",
        region: "",
      }
    };
  }
querySearch(queryString, cb) {
      // 获取区域 
      let region =
        this.checkedItem.province +
        this.checkedItem.city +
        this.checkedItem.region;
      // 请求百度地图web服务api地址
      let url =
        "/place/v2/search?query=" +
        queryString +
        "&region=" +
        region +
        "&output=json&ak=自己的ak";

      this.axios
        .get(url, {
          baseURL: "baiduMapApi",  // 设置代理前缀
        })
        .then((res) => {
          // 获得返回的数据
          let list = res.results;
          // 组装成autoComplete组件所需要的数据结构
          let results = [];
          list.map((item) => {
            results.push({
              value: item.name,
              address: item.address,
              "province":item.province,
              "city":item.city,
              "area":item.area,
            });
          });
          // 调用 callback 返回建议列表的数据
          cb(results);
        });
    },
    handleSelect(item){
      this.checkedItem.province=item.province
        this.checkedItem.city=item.city
        this.checkedItem.region=item.area 
    },