谷歌地图引入流程:
1. 获取API密钥;
console.cloud.google.com/projectsele…
参考最下方的文档
2. 引入googleMapApi库文件;
const script = document.createElement('script')
script.src = 'https://maps.googleapis.com/maps/api/js?libraries=places&key=api-key'
document.head.appendChild(script)// 直接写在html文件中也可
3. 创建googlemap对象:
this.service = new google.maps.places.AutocompleteService()
4. 创建input对象并绑定事件:
<input @input="inputChange" placeholder="请输入地址" v-model="place" />
inputChange:(e)=>{
debounce(()=>{
this.service.getPlacePredictions({
input: e.detail.value,
componentRestrictions:{
country:'nz'
},
}, this.displaySuggestions);
},500) // 记得做防抖处理
}
displaySuggestions(predictions,status){
// api会传入两个参数 一个结果数组 一个状态
if(status != google.maps.places.PlacesServiceStatus.OK || !predictions){
return;
}
const tmpList = [];
predictions.forEach((prediction) => {
const item = {};
item.description = prediction.description;
item.place = prediction.structured_formatting.main_text;
tmpList.push(item);
});
this.addressList = tmpList;
},
5.使用结果 addressList
<view class="item" @click="usePlace(item)" :class="[item.act ? 'item-act':'item-dis']" v-for="(item,index) in addressList" :key="index">
<view class="item-place">
{{item.place}}
</view>
<view class="item-desc">
{{item.description}}
</view>
</view>