1.创建地图
var map = new BMap.Map("container");
var point = new BMap.Point(116.404, 39.915); //中心点
map.centerAndZoom(point, 15);
var marker = new BMap.Marker(point); // 创建标注
map.addOverlay(marker);
this.map=map
this.test()
2.创建一个图片覆盖物点击显示div弹窗
mounted() {
//弹窗div上onclick的方法,需要挂载到window上面,全局访问
window["closeDiv"] = (e) => {
this.closeDiv(e); // 这个也就是我定义的方法
};
},
test() {
let self = this;
let point = new BMapGL.Point(116.404, 39.915);
var myIcon = new BMapGL.Icon("/img/shexiangtou.png",new BMapGL.Size(80, 80));
// 创建标注对象并添加到地图
var marker = new BMapGL.Marker(point, { icon: myIcon });
self.map.addOverlay(marker);
//添加覆盖物点击事件
marker.addEventListener("click", (e) => {
self.imgClick(e);
});
//展现的div html通用模板
//1.click事件只能用原生的onclick,不能用vue的@click,而且方法必须挂载在window上,否则就是underfind 找不到methods里的方法
//2.class的样式,放在style里,不能加scope,要全局的
let strHtml = `<div class="content"><div class='title' style="color:#fff">{{title}}<span onclick=closeDiv({{mapId}}) >x</span></div><div class='content'>{{content}}</div></div>`;
self.$nextTick(() => {
createDiv();
});
// 创建地图上点击图片要显示的内容信息
function createDiv() {
//可用for循环创建多个
let pixel = self.map.pointToOverlayPixel(point); // 获取地图上点的位置坐标left, top
let div = document.createElement("div");
let html = "";
//替换想要的数据
html = strHtml
.replace("{{title}}", "嘻嘻嘻嘻")
.replace("{{mapId}}", "MAP1");
// 修改样式
div.id = "MAP" + 1;// "MAP" + i 循环情况
div.style.backgroundColor = "#EE5D5B";
div.style.display = "none";
div.style.border = "1px solid #BC3B3A";
div.style.position = "absolute";
div.style.height = "200px";
div.style.width = "200px";
div.style.fontSize = "20px";
div.style.wordWrap = "break-word";
div.style.left = pixel.x + "px";
div.style.top = pixel.y + "px";
div.innerHTML = html;
self.map.getPanes().labelPane.appendChild(div); // 将生成的div添加到百度地图
self.map.addOverlay(div);
}
},
//点击x关闭弹窗
closeDiv(a) {
let map1 = document.getElementById(a.id);
map1.style.display = "none";
},
//覆盖物点击出现弹窗
imgClick(e) {
// document.querySelector("#MAP" + 1).style.display = "block";
let map1 = document.getElementById("MAP1");
map1.style.display = "block";
},
缺点:弹窗无法根据地图缩放移动,建议使用infoBox.js
百度地图自定义弹窗infoBox