1. npm安装高德地图
npm i @amap/amap-jsapi-loader --save
2. 组件中引入
import AMapLoader from '@amap/amap-jsapi-loader'
3. 密匙配置
window._AMapSecurityConfig = {
securityJsCode: '8bec9c54c48d3a7cb270ae1d354d3c87'
}
4. 在组件中使用
mounted() {
const _this = this
AMapLoader.load({
key: _this.key,
version: '2.0',
plugins: ['AMap.ToolBar', 'AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.AutoComplete']
})
.then((AMap) => {
// 地图
_this.map = new AMap.Map('container', {
viewMode: '2D',
zoom: 10,
center: [116.410435, 39.905418]
})
_this.map.addControl(new AMap.ToolBar())
// 搜索
_this.placeSearch = new AMap.PlaceSearch({
city: ''
})
// 点击事件
_this.map.on('click', _this.clickMap)
// 逆向地理编码插件
_this.geocoder = new AMap.Geocoder({
// city: "010", //城市设为北京,默认:“全国”
radius: 1000 // 范围,默认:500
})
})
.catch((e) => {
console.log(e)
})
},
5. 点击事件
clickMap(e) {
const longitude = e.lnglat.getLng() // 经度
const latitude = e.lnglat.getLat() // 纬度
const _this = this
_this.geocoder.getAddress([longitude, latitude], (status, result) => {
console.log(status, result)
if (status === 'complete' && result.info === 'OK') {
_this.$emit('change', result, { longitude: longitude, latitude: latitude })
// 传给父组件
}
})
}
6. 父组件接收
changeMap(result, lnglat) {
console.log(result, lnglat)
this.infoForm.nodeAddress = result.regeocode.formattedAddress
}
7. 添加marker
addMarker(address, lnglat) {
// 移除已经创建的marker
if (this.marker) this.map.remove(this.marker)
// 设置地图中心点和缩放级别
this.map.setZoomAndCenter(16, lnglat)
// 自定义标记点
this.marker = new AMap.Marker({
position: lnglat,
anchor: 'top-center',
offset: new AMap.Pixel(-10, -10)
})
// 添加
this.marker.setMap(this.map)
// 设置label
this.marker.setLabel({
direction: 'top-center',
offset: new AMap.Pixel(10, 0), // 设置文本标注偏移量
content: "<div style='width:50px;'>" + address + '</div>' // 设置文本标注内容
})
}
8. 搜索
search(keyword) {
const _this = this
_this.placeSearch.search(keyword, function(status, result) {
_this.$emit('searchChange', result.poiList.pois)
})
},