js baiduMap封装自定义覆盖物类

一、问题引入

使用百度地图添加覆盖物,官方overlay方法覆盖物简单,要实现覆盖物自定义元素,自定义css动画效果等

二、方案

1.自定义覆盖物构造函数,继承baidu overlay

复制代码
function ComplexCustomOverlay(point, marker) {
    console.log("point", point, marker, new BMap.Overlay())
    this._point = point;
    this._marker = marker;

}
ComplexCustomOverlay.prototype = new BMap.Overlay();

// 初始化
ComplexCustomOverlay.prototype.initialize = function (map) {
    console.log('2211');
    this._map = map;
    // 创建一个div
    var div = this._div = document.createElement("div");
    //父级div样式
    div.style.width = "40px";
    div.style.height = "20px";
    div.style.position = "absolute";

    // 创建一个img
    var arrow = document.createElement("img");
    arrow.src = require("../../../assets/image/marker/marker-active.png")
    // 让arrow这个div成为div这个div的子元素   
    div.appendChild(arrow);
    arrow.className = "css_animation";

    // 有marker的话 添加覆盖点
    // if (this._marker) {
    //     map.addOverlay(this._marker);
    // }
    // 在窗格中加入div这个dom元素
    map.getPanes().markerPane.appendChild(div);
    // map.getPanes().labelPane.appendChild(div);
    console.log('div', div);
    return div;
}
ComplexCustomOverlay.prototype.draw = function () {
    var map = this._map;
    var pixel = map.pointToOverlayPixel(this._point);
    console.log('pixel', pixel);
    this._div.style.left = pixel.x - 25 + "px";
    this._div.style.top = pixel.y - 25 + "px";
}

ComplexCustomOverlay.prototype.show = function () {
    if (this._div) this._div.style.display = 'block'
}

ComplexCustomOverlay.prototype.hide = function () {
    if (this._div) this._div.style.display = 'none'
}
export default ComplexCustomOverlay
复制代码

2.页面使用

引入

import CustomOverlay from './CustomOverlay'

使用

  if (this.customOverlay) this.customOverlay.hide()

_this.customOverlay = new CustomOverlay(_this.centerPoint) _this.map.addOverlay(_this.customOverlay) _this.customOverlay.show()

3.根据自定义覆盖物css属性,实现动画效果等

复制代码
.css_animation {
    width: 100%;
    height: 100%;
    animation: loading 2s infinite linear;
    margin-top: 20px;
    margin-left: -5px;
}

@keyframes loading {
    0% {
        transform: scale(0.8);
    }

    50% {
        transform: scale(1.2);
    }

    100% {
        transform: scale(0.8);
    }
}
复制代码

 4.自定义覆盖物绑定自定义事件

// 自定义覆盖物添加事件方法
ComplexCustomOverlay.prototype.addEventListener = function (event, fun) {
    this._div['on' + event] = fun;
}

页面绑定自定义事件方法

this.customOverlay.addEventListener("click", this.showInfo.bind(this, pointInfo)); //覆盖物点击事件
this.customOverlay.addEventListener("click", () => this.showInfo(pointInfo));//覆盖物点击事件

 

posted @   盼星星盼太阳  阅读(83)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示