Preface
The predefined UI controls in the Baidu map API, such as the Navigationcontrol Pan zoom control, the Copyrightcontrol copyright control, the Maptypecontrol map type control ...., which are inherited from the abstract base control, As a result, the properties and methods of control are inherited, so if we need to customize our own controls, we must first inherit control. How do you customize your own controls?
Step One
Customize the control's constructor, specify the default location of the control in the constructor, customize the control's constructor, specify the default location of the control in the constructor, and then have the prototype prototype object of the new control point to the control object to inherit the properties and methods on its prototype chain. For example, create a control with a zoom level below:
/Custom control function Zoomcontrol () { this.defaultanchor=bmap_anchor_top_left;//settings control default location This.defaultoffset = new Bmap.size (60,30);//Set offset}zoomcontrol.prototype= new Bmap.control ();//Inherit Control properties and methods
View Code
Step Two
When adding a custom control through the AddControl () method, the API invokes the Initialize () method inherited from control to initialize the control, so to create the UI control you want, you must rewrite initialize () To build the DOM of the custom control and enclose the corresponding DOM event. Since the DOM of the custom control will eventually be added to the DOM container where the map resides, first we need to call the GetContainer () method to get the map container and then append the custom DOM to the container. Initialize () Method eventually returns the DOM element of the custom control container.
The custom control must implement the Initialize method and return //create a DIV element in this method as a container for the control and add it to the map container ZoomControl.prototype.initialize = function (map) { //Create a DOM element var div = document.createelement ("div"); Add text description div.appendchild (document.createTextNode ("Zoom Level 2")); Set style Div.style.cursor = "pointer"; Div.style.border = "1px solid gray"; Div.style.backgroundColor = "White"; Binding event, click once to enlarge level two Div.onclick = function (e) { map.zoomto (map.getzoom () + 2); } Add DOM elements to the map Map.getcontainer (). appendchild (div); Returns the DOM element to the return div;
View Code
Step Three
A click on a map from this customization to zoom in on 2 levels of control is written out, followed by the use of the same way as the controls defined in the Map API.
/Create a control instance
View Code Drawings
Baidu Maps >> Custom Controls