VUE+高德地图实现地址关联搜索和点标记
需求
1.打开地图定位到当前IP的城市
2.搜索相关地址,将地图中心移动至相关地址
3.在地图上对正确位置标点,并读取地址对应信息
效果如下:
实现
const ininMap = () => {
console.log('地图创建')
AMapLoader.load({
key: '你的key', //api服务key--另外需要在public中使用安全密钥!!!
version: '1.4.4', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete'], // 需要使用的的插件列表
})
.then((AMap) => {
state.map = new AMap.Map('container', {
zoom: 20, //级别
resizeEnable: true,
})
AMap.plugin(
['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Geocoder'],
function () {
//输入框连锁
const autoOptions = {
input: 'tipinput', // 使用联想输入的input的id
}
const autocomplete = new AMap.Autocomplete(autoOptions)
//下拉框置顶
const xia = document.getElementsByClassName('amap-sug-result')
for (let i = 0; i < xia.length; i++) {
const element = xia[i]
element.style.zIndex = 2500
}
AMap.event.addListener(autocomplete, 'select', function (e) {
const lngLat = [e.poi.location.lng, e.poi.location.lat]
state.map.setCenter(lngLat)
})
//点击标点
state.map.on('click', (e) => {
state.markersLngLat = [e.lnglat.getLng(), e.lnglat.getLat()]
if (state.marker != null) {
state.marker.setMap(null)
state.marker = null
}
state.marker = new AMap.Marker({
position: state.markersLngLat,
})
state.marker.setMap(state.map)
//定位获取地址
const geocoder = new AMap.Geocoder({
radius: 1000,
extensions: 'all',
})
geocoder.getAddress(
state.markersLngLat,
function (status, result) {
if (status === 'complete' && result.info === 'OK') {
console.log(result)
//你的业务逻辑
} else {
console.log('地址查询错误,请重新标点')
}
}
)
})
}
)
})
.catch((e) => {
console.log(e)
})
}