Vue中使用高德地图,包含点击更新坐标点、搜索关键字提示、点击搜索结果同步更新坐标点。
initMap (): void {
AMapLoader.load({
key: '', // 申请好的Web端开发者Key,首次调用 load 时必填
version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
plugins: [
'AMap.Scale',
'AMap.ToolBar',
'AMap.Geolocation',
'AMap.AutoComplete'
] // 需要使用的的插件列表,如比例尺'AMap.Scale'等
}).then((AMap) => {
this.AMap = AMap
const self = this
self.map = new AMap.Map('map-container', { // 设置地图容器id
viewMode: '3D', // 是否为3D地图模式
zoom: 14, // 初始化地图级别
center: [self.longitude || 116.39, self.latitude || 39.9] // 初始化地图中心点位置
})
self.map.addControl(new AMap.Scale()) // 在图面添加比例尺控件,展示地图在当前层级和纬度下的比例尺
self.map.addControl(new AMap.ToolBar()) // 在图面添加工具条控件,工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
self.map.addControl(new AMap.Geolocation()) // 在图面添加定位控件,用来获取和展示用户主机所在的经纬度位置
AMap.plugin('AMap.Geocoder', function () {
self.geoCoder = new AMap.Geocoder()
})
self.updateCoordinates() // 更新坐标
// self.map.on('click', self.showInfoClick) // 添加点击事件
const autoOptions = { input: 'tipinput' } // 输入提示
const auto = new AMap.AutoComplete(autoOptions)
AMap.Event.addListener(auto, 'select', self.select) // 注册监听,当选中某条记录时会触发
}).catch((e: any) => {
console.log(e)
})
}
// 选择搜索中的某一项
select (e: Record<string, any>): void {
this.longitude = e.poi.location.lng
this.latitude = e.poi.location.lat
this.address = e.poi.district + e.poi.address
this.addressName = e.poi.name
this.removeMarker() // 删除原坐标
this.resolveAddress() // 解析地址
this.updateCoordinates('isSelect') // 更新坐标
}
// 更新坐标
updateCoordinates (isSelect?: string): void {
const AMap = this.AMap
const marker = new AMap.Marker({
map: this.map,
position: new AMap.LngLat(this.longitude || 116.39, this.latitude || 39.9) // 创建时没有坐标 给个初始经纬度坐标
})
this.markers.push(marker) // 将 markers 添加到地图
if (isSelect) {
const position = new AMap.LngLat(this.longitude, this.latitude)
this.map.setZoomAndCenter(18, position) // 传入经纬度,设置地图中心点
}
}
// 高德SDK解析地址
resolveAddress ():void {
const self = this
self.geoCoder.getAddress([this.longitude, this.latitude], function (status:any, result:any) {
if (status === 'complete' && result.info === 'OK') {
if (result && result.regeocode) {
const { province, city } = result.regeocode.addressComponent
// 自动定位遍历匹配省市
self.proviceList.forEach((item:any) => {
if (item.name === province) (self.currentProvince = item.id)
})
self.getCityList(city)
}
}
})
}
// 删除之前后的标记点
removeMarker (): void {
if (this.markers) {
this.map.remove(this.markers)
}
}