效果图:拖拽前和拖拽后
目录
一、完成地图步骤
百度地图文档地址:地图 JS API | 百度地图API SDK
1、在index.html引入百度地图
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=你的密钥"></script>
2、创建地图容器,容器一定要设置宽高
<template>
<div class='loction'>
<div>位置信息:{{locationMsg}}</div>
<!-- 地图容器 -->
<div id="allmap"></div>
</div>
</template>
<style>
.loction{
width: 300px;
height: 300px;
}
#allmap{
width: 300px;
height: 300px;
}
</style>
3、创建地图实例
const map = new window.BMap.Map('allmap') // 创建Map实例
// 开启SDK辅助定位获取当前位置信息
const getLocation = new window.BMap.Geolocation()
getLocation.enableSDKLocation()
getLocation.getCurrentPosition((position) => { // position中是获取到的定位相关数据
// 获取城市和省
const city = position.address.city
const province = position.address.province
// 获取经度和纬度
const latitude = position.latitude
const longitude = position.longitude
this.locationMsg = province + city
const point = new window.BMap.Point(position.point) // 设置中心点坐标
map.centerAndZoom(point, 15) // 地图初始化,同时设置地图展示级别为15
const marker= new window.BMap.Marker(position.point) // 创建标注
map.addOverlay(marker) // 将标注添加到地图中
map.panTo(position.point, 15) //让指定位置移动到地图中心
// 开启marker拖拽并监听拖拽后的位置信息
marker.enableDragging() // 可拖拽标注
const _this = this
marker.addEventListener('dragend', function (e) {
// alert('当前位置:' + e.point.lng + ', ' + e.point.lat)
const nowPoint = marker.getPosition() // 拖拽完成之后坐标的经纬度
console.log(nowPoint, '拖拽后的经纬度')
map.centerAndZoom(nowPoint, 15)
// 用所定位的经纬度查找所在地省市街道等信息
const gc = new window.BMap.Geocoder()
gc.getLocation(nowPoint, function (rs) {
console.log(rs, '拖拽后的位置')
_this.locationMsg = rs.address
})
})
}, () => {
this.locationMsg = '定位失败!'
}, { provider: 'baidu' })
二、百度地图踩过的一些坑
1、'BMap' is not defined报错
这个是和引入地图有关,官方文档的写法是var map = new BMapGL.Map('container')。如果是在index.html中引入的js文件,那么需要写成var map = new window.BMapGL.Map('container');
2、标注没有出现在地图中间而是左上角
是因为再次让地图显示时,地图已经显示了,但标注还没创建好,用一个setTimeout包裹一下就好了。
setTimeout(() => {
map.panTo(this.newPosition, 16)
},200)
3、定位不准确
使用sdk辅助定位是相对来说比较准确的,开发时只能在电脑上测试,电脑没有gps定位,所以有偏差很正常,打包上线后用手机测试就会很准确了。
这是我入职前端遇到的第一个项目需求,从啥也不会到完成,经历了好几天,出现过各种bug,然后又非常害怕被老板开除。整个过程充满焦虑,紧张和不安,到完成终于可以松一口气了。所以记录一下。希望能帮到大家。如果有更好的办法欢迎大家指教!