项目有个需求,在弹窗内需要一个输入框,输入地址调用百度地图api进行搜索,但是不需要用到地图。
在百度上找的资料全是需要地图的,这里提供一个解决方法,希望适用。
这是html
<div>
<el-autocomplete
style="width: 100%"
v-model="address"
popper-class="autoAddressClass"
:placeholder="placeholder"
:disabled="disabled"
:fetch-suggestions="toSearch"
:trigger-on-focus="false"
clearable
@select="handleSelect"
@clear="clear"
>
<template slot-scope="{ item }">
<i class="el-icon-search fl mgr10"></i>
<div style="overflow: hidden">
<div class="title">{{ item.name }}</div>
<span class="address ellipsis">{{ item.address }}</span>
</div>
</template>
</el-autocomplete>
</div>
这是js
name: "MapAddress",
data() {
return {
address: "",
mapAddress: [],
};
},
props: {
city: {
type: String,
default: "长沙",
},
placeholder: {
type: String,
default: "请输入详细地址",
},
disabled: {
type: Boolean,
default: false,
},
value: {
type: String,
default: "",
},
},
watch: {
value: {
handler(val) {
if (val != undefined && val != "") {
this.address = val;
}
},
deep: true,
immediate: true,
},
},
methods: {
async toSearch(str, cb) {
let that = this;
await this.baidu_api_point(str, callbackData);
function callbackData(data) {
that.mapAddress = data.results;
cb(that.mapAddress);
}
},
handleSelect(item) {
this.$emit("callbackMap", item.address);
},
clear() {
this.$emit("callbackMap", "");
},
这个解决跨域
baidu_api_point(path, callback) {
//跨域调用百度api
//注意这里挂载在了window上
window.callbackData = callback;
let url = `https://api.map.baidu.com/place/v2/search?query=${path}®ion=${this.city}&page_size=20&output=json&ak=GwgzHwgqUGzFNZpRClR63mzn93RH0clK&callback=callbackData`;
let fetchJsonp = function (url) {
let body = document.getElementsByTagName("body")[0];
//插入一个script
let script = document.createElement("script");
script.setAttribute("src", url);
script.setAttribute("id", "mapApi");
body.appendChild(script);
};
fetchJsonp(url);
},