项目有用到Google autocomplete for addresses and search, 这个是谷歌官网文档
,因为项目用的是vue,有dalao已经写好的有组件了叫做:vue-google-autocomplete,可在仓库地址 查看具体用法。
效果图:
google autocomplete
1. 获取key后引入脚本文件
先在index.html的head标签中引入api js文件,YOUR_API_KEY_HERE可以在google map api官网获取。
<!DOCTYPE html>
<html>
<head>
…
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&libraries=places"></script>
</head>
<body>
…
</body>
</html>
注意: 这个js最好写在其他js的引入文件前,我就遇到
map和recaptcha一起引入,然后后引入的map,结果报错,后来换个顺序就可以了。
2. 安装
安装: npm / yarn 自己选一个
$ npm install vue-google-autocomplete --save
or
$ yarn add vue-google-autocomplete
3. 使用
在要使用的组件中先导入
import VueGoogleAutocomplete from 'vue-google-autocomplete'
不要忘记加入 components 中.
在template中使用
<vue-google-autocomplete
id="mapNew"
classname="txt"
ref="newAddressElem"
:class="{error: data.newAddress==''}"
:placeholder="placeholder text"
country="hk"
@placechanged="getAddressData"
@inputChange="updateNewAddress"
>
</vue-google-autocomplete>
country是指定城市,可以有个字符串也可以有个数组,具体可看github。因为没有v-model,所以可以通过inputChange事件实现获取用户输入的值。
data() {
return {
newAddress: ''
}
},
methods: {
getAddressData(addressData, placeResultData, id) {
console.log(addressData, placeResultData, id)
},
updateNewAddress(val) {
this.newAddress = val.newVal
}
}
inputChange事件是文本框内容改变时触发,包括用户输入的内容。placechanged事件是下拉选项选择后触发,用户输入不会触发。
还有一些其它花里胡哨的属性和事件,官网也没有详写😿。
-- End --











网友评论