实现一个带搜索功能的地图,并且获取选取的地点信息,下面我们开始吧
效果图:
代码:
<script>
export default {
name: 'map-show',
data () {
return {
map: null,
dataRes: {}
}
},
mounted () {
this.initMap()
},
methods: {
// 实例化地图
initMap () {
const AMap = window.AMap
this.map = new AMap.Map('container', {
resizeEnable: true,
zoom: 12,
center: [120.204388,30.244759]
})
},// 输出数据
output(name) {
// name为字符串,'北京'、'上海'、'杭州'
// 位置联想搜索,并标记
let that = this
const AMap = window.AMap
AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'],function(){
let autoOptions = {
city: name, // 城市,默认全国
input: 'keyword' // 使用联想输入的input的id
}
let autocomplete= new AMap.Autocomplete(autoOptions)
const placeSearch = new AMap.PlaceSearch({
city: name,
map: new AMap.Map('container', {
resizeEnable: true
})
})
AMap.event.addListener(autocomplete, 'select', function(res) {
const data = res.poi
// 组合需要的数据
that.dataRes = {
location: data.location.lng + ',' + data.location.lat,
address: data.name,
addressDetail: data.district + '' + data.address
}
// 搜索
placeSearch.search(data.name)
})
})
}
}
}
</script>
<style>
// 设置权重值,使搜索下拉选项不被隐藏
.amap-sug-result {
z-index: 9999 !important;
}
</style>