官網栗子:http://lbsyun.baidu.com/jsdemo.htm#b0_6
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
body, html {width: 100%;height: 100%;margin:0;font-family:"微軟雅黑";}
#allmap{width:100%;height:500px;}
p{margin-left:5px; font-size:14px;}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的密鑰"></script>
<title>添加自定義控件</title>
</head>
<body>
<div id="allmap"></div>
<p>在地圖左上角添加"放大2級"自定義控件,雙擊放大地圖2級</p>
</body>
</html>
<script type="text/javascript">
// 百度地圖API功能
var map = new BMap.Map("allmap");
map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);
// 定義一個控件類,即function
function ZoomControl(){
// 默認停靠位置和偏移量
this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
this.defaultOffset = new BMap.Size(10, 10);
}
// 通過JavaScript的prototype屬性繼承於BMap.Control
ZoomControl.prototype = new BMap.Control();
// 自定義控件必須實現自己的initialize方法,並且將控件的DOM元素返回
// 在本方法中創建個div元素作為控件的容器,並將其添加到地圖容器中
ZoomControl.prototype.initialize = function(map){
// 創建一個DOM元素
var div = document.createElement("div");
// 添加文字說明
div.appendChild(document.createTextNode("放大2級"));
// 設置樣式
div.style.cursor = "pointer";
div.style.border = "1px solid gray";
div.style.backgroundColor = "white";
// 綁定事件,點擊一次放大兩級
div.onclick = function(e){
map.setZoom(map.getZoom() + 2);
}
// 添加DOM元素到地圖中
map.getContainer().appendChild(div);
// 將DOM元素返回
return div;
}
// 創建控件
var myZoomCtrl = new ZoomControl();
// 添加到地圖當中
map.addControl(myZoomCtrl);
</script>