高德地圖自帶的,根據(jù)用戶輸入的地址撵彻,進行模糊搜索穿铆,用戶進行選擇定位
用vue
以及element-ui
實現(xiàn)的您单,
頁面部分布局
<div class="location-wrap">
<div id="location"></div>
<div class="search">
<el-input
id="tip-input"
size="small"
class="search-input"
placeholder="請輸入地址"
prefix-icon="el-icon-search"
v-model="address"
:clearable="true"
@input="mapLocation"
>
</el-input>
<ul class="list" v-show="searchMsg">
<li v-for="(item, index) in list" :key="index" @click="selectAddress(item)">{{item.name}}</li>
</ul>
</div>
</div>
js部分
在mounted時候,加載地圖
<script>
import MP from '這個加載地圖文件荞雏,訪問也在簡書中'
let map = '' // 定義地圖
let marker = '' // 定義一個標(biāo)記
export default {
data () {
return {
mapKey: '這是你的地圖key',
address: '', // 輸入地址
list: [], // 模糊搜索的list
searchMsg: false, // list下拉框的顯示隱藏
lnglat: {} // 存儲點擊的經(jīng)緯度
}
},
created () {
},
async mounted () {
await MP (this.mapKey)
this.map()
this.clickMap() // 地圖上的點擊事件
},
methods: {
// 將獲取到的地址傳回到父組件
handleChange (val) {
this.$emit('address', val)
},
// 下拉框中的選擇
selectAddress (val) {
this.address = `${val.district}${val.name}`
this.handleChange(`${val.district}${val.name}`)
},
// 初始化地圖
map () {
map = new AMap.Map('location', {
resizeEnable: true,
zoom: 14
})
},
// input事件
mapLocation () {
// 使用高德地圖的自動補全和搜索的功能
map.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], () => {
// 實例化Autocomplete
var autoOptions = {
city: '全國'
}
let autoComplete = new AMap.Autocomplete(autoOptions)
autoComplete.search(this.address, (status, result) => {
if (result && result.info === 'OK') {
this.list = result.tips
this.searchMsg = true
this.placeSearch(this.list.length && this.list[0].name)
}
})
})
},
placeSearch (value) {
let placeSearch = new AMap.PlaceSearch({
city: '全國',
map: map
})
placeSearch.search(value)
},
// 地圖上的點擊事件虐秦,根據(jù)點擊位置平酿,記一個mark,點擊新的位置,去掉之前的mark,記錄最新的
clickMap () {
map.on('click', (e) => {
if (JSON.stringify(this.lnglat) !== '{}') {
this.mark('remove', this.lnglat)
}
this.lnglat = e.lnglat
this.mark('add', e.lnglat)
map.plugin(['AMap.Geocoder'], () => {
let geocoder = new AMap.Geocoder({
radius: 1000,
extensions: 'all'
})
geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], (status, result) => {
if (result && result.info === 'OK') {
this.address = `${result.regeocode.formattedAddress}`
this.handleChange(`${result.regeocode.formattedAddress}`)
this.close()
}
})
})
})
},
// 標(biāo)記的新增和刪除
mark (type, value) {
if (type === 'remove') {
return map.remove(marker)
}
marker = new AMap.Marker({
position: new AMap.LngLat(value.lng, value.lat),
title: '北京'
})
map.add(marker)
}
}
}
</script>
css樣式悦陋,使用的less
.location-wrap {
position: relative;
width: 100%;
height: 500px;
}
#location {
width: 100%;
height: 100%;
}
.search {
position: absolute;
right: 10px;
top: 10px;
.el-input {
width: 400px;
}
.list {
width: 380px;
// height: 300px;
background: #ffffff;
padding: 0 10px;
color: #333;
font-size: 14px;
}
li {
line-height: 40px;
cursor: pointer;
}
}
提示:高德地圖jsapi的地址