注册账号并申请Key
- 可查看官网入门教程 官网入门教程
需要添加两个key,
Web端(JS API)和Web服务,如下图所示
开发准备
- 安装地图组件
npm i @amap/amap-jsapi-loader --save
- 页面引入
部分代码如下,仅供参考
- 初识化地图
AMapLoader.load({
key: mapJsKey, // 申请好的Web端开发者Key,首次调用 load 时必填
// plugins,一些插件,可以按需使用调用
plugins: [
'AMap.ToolBar',
'AMap.scale',
'AMap.PlaceSearch',
'AMap.MouseTool',
'AMap.Geolocation',
'AMap.Geocoder',
'AMap.AutoComplete',
'AMap.Circle' // 圆形
]
}).then((AMap) => {
let initData = {
// 设置地图容器id
viewMode: '2D', // 是否为3D地图模式
zoom: 18, // 初始化地图级别
zoomEnable: true,
resizeEnable: true,
center: [], //自定义设置
enableHighAccuracy: true
}
that.marker = new AMap.Marker({}) // 设置点标记
that.map = new AMap.Map('map-container', initData) //添加到对应的容器中
})
- 获取当前位置
let that = this
that.map.plugin('AMap.Geolocation', function () {
const geolocation = new AMap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默认:true
timeout: 5000, // 超时时间
maximumAge: 0,
showCircle: false,
convert: true, // 自动偏移坐标,偏移后的坐标为高德坐标,默认:true
showMarker: false, // 定位成功后在定位到的位置显示点标记,默认:true
panToLocation: true, // 定位成功后将定位到的位置作为地图中心点,默认:true
zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
})
that.map.addControl(geolocation)
geolocation.getCurrentPosition(function (status, result) {
if (status === 'complete') {
that.circle = new AMap.Circle({
center: [result.position.lng, result.position.lat], // 圆心位置
radius: 1000,
fillColor: 'rgba(103,182,255,.5)', // 圆形填充颜色
strokeColor: '#5898ff', // 描边颜色
strokeWeight: 2, // 描边宽度
})
that.marker.setPosition([
parseFloat(result.position.lng),
parseFloat(result.position.lat),
])
// 添加标记点
that.map.add(that.marker)
// 地图添加圆形圈圈
that.map.add(that.circle)
} else {
Notify({
type: 'warning',
message: '获取当前位置失败',
})
}
})
})
- 获取附近的地址信息
onHandleSearch (e) {
let that = this
try {
axios({
method: 'get',
url: 'https://restapi.amap.com/v5/place/around?parameters',
params: {
key: mapServerKey,
keywords: this.searchAddr,
location: `${this.currentSelect.lng},${this.currentSelect.lat}`, // 输入位置信息
radius: 1000 // 搜索的半径
}
})
.then(function (response) {
const { pois } = response.data
})
.catch((err) => {
Notify({ type: 'danger', message: '查询失败' })
})
} catch (err) {}
}
在2021年12月02日申请以后的key需要配合您的安全密钥一起使用)
一些爬坑问题
- 因为我们这边一开始没有新增下面的代码,获取当前定位不准确,会相差一定的距离
window._AMapSecurityConfig = {
securityJsCode:'balallall',
}
- 获取当前位置方案选择
- navigator.geolocation.getCurrentPosition
- geolocation.getCurrentPosition
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(pos) => {
this.mapData = {
lat: pos.coords.latitude,
lng: pos.coords.longitude,
}
},
(err) => {
// 获取当前位置失败操作
console.log(err)
Notify({
type: 'warning',
message: '获取地址信息失败',
})
},
{
enableHighAccuracy: true,
timeout: 3000,
maximumAge: 0,
},
)
}
- 更多内容参考 高德地图 JSAPI 2.0
ps: 有任何问题欢迎一起探讨呀🤓🤓🤓