function(){ alert(‘click‘); }); 同理

时间:2022-03-30 08:51:01

  给marker、lable、circle等Overlay添加事件很简单,直接addEventListener即可。那么,自界说笼罩物的事件应该如何添加呢?我们一起来看一看~

-----------------------------------------------------------------------------------------

一、界说结构函数并担任Overlay

// 界说自界说笼罩物的结构函数
function SquareOverlay(center, length, color){
this._center = center;
this._length = length;
this._color = color;
}
// 担任API的BMap.Overlay
SquareOverlay.prototype = new BMap.Overlay();

二、初始化自界说笼罩物

// 实现初始化要领
SquareOverlay.prototype.initialize = function(map){
// 生存map东西实例
this._map = map;
// 创建div元素,作为自界说笼罩物的容器
var div = document.createElement("div");
div.style.position = "absolute";
// 可以按照参数设置元素外不雅观
div.style.width = this._length + "px";
div.style.height = this._length + "px";
div.style.background = this._color;
// 将div添加到笼罩物容器中
map.getPanes().markerPane.appendChild(div);
// 生存div实例
this._div = div;
// 需要将div元素作为要领的返回值,当挪用该笼罩物的show、
// hide要领,或者对笼罩物进行移除时,API都将操纵此元素。
return div;
}

三、绘制笼罩物

// 实现绘制要领
SquareOverlay.prototype.draw = function(){
// 按照地舆坐标转换为像素坐标,并设置给容器
var position = this._map.pointToOverlayPixel(this._center);
this._div.style.left = position.x - this._length / 2 + "px";
this._div.style.top = position.y - this._length / 2 + "px";
}

四、添加笼罩物

//添加自界说笼罩物
var mySquare = new SquareOverlay(map.getCenter(), 100, "red");
map.addOverlay(mySquare);



五、给自界说笼罩物添加事件

1、显示事件

SquareOverlay.prototype.show = function(){
if (this._div){
this._div.style.display = "";
}
}

添加完以上显示笼罩物事件后,只需要下面这句话,就可以显示笼罩物了。

mySquare.show();

2、隐藏笼罩物

// 实现隐藏要领
SquareOverlay.prototype.hide = function(){
if (this._div){
this._div.style.display = "none";
}
}

添加完以上code,只需使用这句话,即可隐藏笼罩物。

mySquare.hide();

3、转变笼罩物颜色

SquareOverlay.prototype.yellow = function(){
if (this._div){
this._div.style.background = "yellow";
}
}

上面这句话,是把笼罩物的配景颜色改成黄色,使用以下语句即可生效:

mySquare.yellow();

“第五部分、给笼罩物添加事件”小结:

我们在舆图上添加了一个红色笼罩物,然后分袂添加“显示、隐藏、转变颜色”的事件。示意图如下:

function(){ alert(‘click‘); }); 同理

那么,我们需要在html里,先写出map的容器,和3个按钮。

<div></div>
<p>
<input type="button" value="移除笼罩物" />
<input type="button" value="显示笼罩物" />
<input type="button" value="酿成黄色" />
</p>

然后,,在javascript中,添加这三个函数:

// 实现显示要领
SquareOverlay.prototype.show = function(){
if (this._div){
this._div.style.display = "";
}
}
// 实现隐藏要领
SquareOverlay.prototype.hide = function(){
if (this._div){
this._div.style.display = "none";
}
}

//转变颜色的要领
SquareOverlay.prototype.yellow = function(){
if (this._div){
this._div.style.background = "yellow";
}
}





六、如何给自界说笼罩物添加点击事件(这章重要!很多人问的)

好比,我们给自界说笼罩物点击click事件。首先,需要添加一个addEventListener 的事件。如下:

SquareOverlay.prototype.addEventListener = function(event,fun){
this._div[‘on‘+event] = fun;
}

再写该函数里面的参数,好比click。这样就跟百度舆图API里面的笼罩物事件一样了。

mySquare.addEventListener(‘click‘,function(){
alert(‘click‘);
});

同理,添加完毕addEventListener之后,还可以添加其他鼠标事件,好比mou搜索引擎优化ver。

mySquare.addEventListener(‘mousemover‘,function(){
alert(‘鼠标移上来了‘);
});

七、全部源代码

自界说笼罩物

八、感谢感动大家撑持!

API常见问题总结贴: 

【百度舆图API】如何给自界说笼罩物添加事件