功能描述
- 地图选点并添加标注
-
根据选择的行政区地位地图中心点
image.png
在页面最前面引入百度地图js,否则可能导致百度地图AK无法读取
创建地图容器元素
需要设置容器样式大小,不然无法展示地图
定义对象
data: function () {
return {
map: {}, //百度地图对象
infoWindow: {}, //地图信息窗口对象
marker: {},
markerPng: "https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png", //地图位置图标
}
},
初始化百度地图
//初始化百度地图
initBaiduMap(){
let _this = this;
this.map = new BMapGL.Map("baiduMap");
// 创建地图实例
let point = new BMapGL.Point(116.404, 39.915);
// 创建点坐标
this.map.centerAndZoom(point, 12);
//开启鼠标滚轮缩放
this.map.enableScrollWheelZoom(true);
//监听地图单击事件
this.map.addEventListener('click', function (e) {
_this.marker = {};
_this.setAddress(e.latlng);
})
},
根据经纬度获取地址并添加标注
//根据经纬度获取地址并添加标注
setAddrAndMarker(lnglat) {
let _this = this;
let lat = lnglat.lat;
let lng = lnglat.lng;
let point = new BMapGL.Point(lng, lat);
let geocoder = new BMapGL.Geocoder();
geocoder.getLocation(point, function(GeocoderResult) {
let address = '';
if (GeocoderResult != null) {
address = GeocoderResult.address;
_this.company.lat = lat;
_this.company.lon = lng;
} else {
address = '未查询到详细地址';
}
_this.company.company_address = address;
_this.addPointMarker(lng, lat, address); //添加标注
});
}
添加标注
- 如果报错,则是页面未加载完成,先初始化了地图,可用setTimeout()函数延时
Uncaught TypeError: Cannot read property 'width' of undefined
//添加标注
addPointMarker(lngi, lati, address){
let _this = this;
//构建点对象
let point = new BMapGL.Point(lngi, lati);
let anchor = new BMapGL.Size(11.5,35);
let url = this.markerPng;
let iconSize = new BMapGL.Size(23, 35);
let imageSize = new BMapGL.Size(23, 25);
let icon = new BMapGL.Icon(url, iconSize, {
anchor: anchor
})
icon.setImageSize(imageSize);
_this.marker = new BMapGL.Marker(point, {
enableClicking: true,
icon: icon
});
let size = new BMapGL.Size(0, -30);
let content = ""+"地址:"+address+"
"
_this.infoWindow = new BMapGL.InfoWindow(content, {
enableAutoPan: true,
offset: size,
});
_this.delMars();
_this.map.addOverlay(_this.marker);
_this.setMapCenter(point);
_this.map.openInfoWindow(_this.infoWindow, point);
},
删除上次搜索的标注
delMars(){
this.map.clearOverlays();
}
设置中心点
//设置地图中心
setMapCenter(point)
{
this.map.setCenter(point);
}
根据地址解析坐标
//根据地址解析坐标
getPoint(province, city, country){
let _this = this;
let address = province + city + country;
//创建地址解析器实例
var myGeo = new BMapGL.Geocoder();
// 将地址解析结果显示在地图上,并调整地图视野
myGeo.getPoint(address, function(point){
if(point){
let lat = point.lat;
let lng = point.lng;
_this.company.lat = lat;
_this.company.lon = lng;
_this.setMapCenter(point);
}else{
alert('您选择的地址没有解析到结果!');
}
}, city)
}