效果
代码
首先在index.html中引入谷歌地图资源
<script src="https://maps.googleapis.com/maps/api/js?key='你的api密钥'&libraries=places"></script>
页面中
<template><div class="pac-card div-style" id="pac-card"><div id="map" class="flex-item1"></div><div id="pac-container" class="flex-item2"><el-inputv-model="localValue"ref="autocompleteInput"type="text"placeholder="输入地址"@input="handleInput"/><ulv-if="predictions.length != 0 && localValue != ''"class="autocomplete-list"><listyle="list-style: none"v-for="prediction in predictions":key="prediction.place_id"@click="selectPrediction(prediction)">{{ prediction.description }}</li></ul></div></div>
</template><script>
export default {name: "addressMap",data() {return {localValue: "",map: "",marker: "",longitude: -73.98633,latitude: 40.749933,predictions: [], // 存储搜索框提示的预测结果};},methods: {selectPrediction(prediction) {this.localValue = prediction.description;this.predictions = [];const that = this;// 创建 PlacesService 对象const placesService = new google.maps.places.PlacesService(map);// 获取地点的 Place IDconst placeId = prediction.place_id;// 发起 Places API 请求placesService.getDetails({ placeId: placeId }, function (place, status) {if (status === google.maps.places.PlacesServiceStatus.OK) {// 获取地点的经纬度坐标that.latitude = place.geometry.location.lat();that.longitude = place.geometry.location.lng();that.initMap();} else {alert("无法找到该地点!");}});},handleInput() {const autocompleteService = new google.maps.places.AutocompleteService();autocompleteService.getPlacePredictions({ input: this.localValue },(predictions, status) => {if (status === google.maps.places.PlacesServiceStatus.OK) {this.predictions = predictions;} else {this.predictions = [];}});},initMap() {const map = new google.maps.Map(document.getElementById("map"), {center: { lat: this.latitude, lng: this.longitude },zoom: 13,mapTypeControl: false,});},},mounted() {this.initMap();},
};
</script><!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
#map {overflow: hidden;width: 300px;height: 400px;margin: 0;
}
.div-style {display: flex;
}
.flex-item1 {flex: 2;
}
.flex-item2 {flex: 1;
}
.autocomplete-list {height: 200px;overflow: auto;ul {li {margin: 10px 0;}}
}
</style>