search
HomeBackend DevelopmentPHP TutorialBaidu Map API-Add event method to custom overlay_PHP tutorial

Baidu Map API-Add event method to custom overlay_PHP tutorial

Jul 20, 2016 am 11:10 AM
one timeeventaboutmapapplicationarticlemethodAdd toBaiduofSimplecustomizecover

This article briefly introduces the application of Baidu Maps. Here I introduce a function that is to add an event method on a layer you set. Please refer to it if necessary.

It is very simple to add events to overlays such as marker, label, circle, etc., just addEventListener directly. So, how to add events for custom overlays? Let’s take a look~

------------------------------------------------ -------------------------------------------------one , define the constructor and inherit Overlay

 代码如下 复制代码
// 定义自定义覆盖物的构造函数
function SquareOverlay(center, length, color){
this._center = center;
this._length = length;
this._color = color;
}
// 继承API的BMap.Overlay
SquareOverlay.prototype = new BMap.Overlay(); 2. Initialize the custom overlay

 代码如下 复制代码
// 实现初始化方法  <br>SquareOverlay.prototype.initialize = function(map){  <br>// 保存map对象实例  <br> this._map = map;      <br> // 创建div元素,作为自定义覆盖物的容器  <br> var div = document.createElement("div");  <br> div.style.position = "absolute";      <br> // 可以根据参数设置元素外观  <br> div.style.width = this._length + "px";  <br> div.style.height = this._length + "px";  <br> div.style.background = this._color;    <br> // 将div添加到覆盖物容器中  <br> map.getPanes().markerPane.appendChild(div);    <br> // 保存div实例  <br> this._div = div;    <br> // 需要将div元素作为方法的返回值,当调用该覆盖物的show、  <br> // hide方法,或者对覆盖物进行移除时,API都将操作此元素。  <br> return div;  <br>}
3. Draw the overlay

 代码如下 复制代码
// 实现绘制方法  <br>SquareOverlay.prototype.draw = function(){  <br>// 根据地理坐标转换为像素坐标,并设置给容器 <br> var position = this._map.pointToOverlayPixel(this._center);<br> this._div.style.left = position.x - this._length / 2 + "px";  <br> this._div.style.top = position.y - this._length / 2 + "px";  <br>}
4 , Add overlay

 代码如下 复制代码
//添加自定义覆盖物  <br>var mySquare = new SquareOverlay(map.getCenter(), 100, "red");  <br>map.addOverlay(mySquare);
5. Add events to custom overlays 1. Display events

 代码如下 复制代码
SquareOverlay.prototype.show = function(){  <br> if (this._div){  <br>   this._div.style.display = "";  <br> }  <br>}
After adding the above display overlay event, you only need the following sentence to display the overlay.

 代码如下 复制代码
mySquare.show();
2. Hide the overlay
// 实现隐藏方法  <br>
 代码如下 复制代码
SquareOverlay.prototype.hide = function(){
if (this._div){
this._div.style.display = "none";
}
}
添加完以上code,只需使用这句话,即可隐藏覆盖物。
mySquare.hide();
3. Change the color of the overlay

 代码如下 复制代码
SquareOverlay.prototype.yellow = function(){  <br> if (this._div){  <br>    this._div.style.background = "yellow"; <br> }     <br>}
The above sentence If you want to change the background color of the overlay to yellow, use the following statement to take effect:
mySquare.yellow();
Summary of "Part 5, Adding Events to the Overlay": We added a red overlay on the map. Then add "show, hide, change color" events respectively. The schematic diagram is as follows: Then, we need to first write the map container and 3 buttons in html.

 代码如下 复制代码
<div style="width:520px;height:340px;border:1px solid gray" id="container"></div><br><p><br>    <input type="button" value="移除覆盖物" onclick="mySquare.hide();"><br>    <input type="button" value="显示覆盖物" onclick="mySquare.show();"><br>    <input type="button" value="变成黄色" onclick="mySquare.yellow();"><br></p>
Then, in javascript, add these three functions:

 代码如下 复制代码
// 实现显示方法  
SquareOverlay.prototype.show = function(){ <br> if (this._div){ <br> this._div.style.display = ""; <br> } <br>}
// 实现隐藏方法 <br>SquareOverlay.prototype.hide = function(){
if (this._div){
this._div.style.display = "none";
}
}

//改变颜色的方法
SquareOverlay.prototype.yellow = function(){ <br> if (this._div){ <br> this._div.style.background = "yellow"; <br> } <br>}

6. How to add a click event to a custom overlay (This chapter is important! Many people ask) For example, we add a click event to a custom overlay. First, you need to add an addEventListener event. As follows:

 代码如下 复制代码
SquareOverlay.prototype.addEventListener = function(event,fun){<br>    this._div['on'+event] = fun;<br>}
Then write the parameters in the function, such as click. This is the same as the overlay event in Baidu Map API.

 代码如下 复制代码
mySquare.addEventListener('click',function(){<br>    alert('click');<br>});
Similarly, after adding addEventListener, you can also add other mouse events, such as mouseover.

 代码如下 复制代码
mySquare.addEventListener('mousemover',function(){<br>    alert('鼠标移上来了');<br>});
7. All source codesCustom overlay

 代码如下 复制代码
1
2
3
4
5 自定义覆盖物的点击事件
6
7
8
9

10


11
12
13
14


15
16
17
八、感谢大家支持!API FAQ summary post:http://tieba.baidu.com/p /1147019448

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444736.htmlTechArticleThis article briefly introduces the application of Baidu Maps. Here I introduce a function that is based on the layer you define. Add an event method above, refer to it if necessary. To marker,...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use