1.申請(qǐng)密鑰(ak)
首先要注冊(cè)開發(fā)者:
激活后即可申請(qǐng)密鑰:
2.加載API JS文件
- 使用V1.4及以前版本的引用方式:
<script src="http://api.map.baidu.com/api?v=1.4" type="text/javascript"></script>
- 使用V2.0版本的引用方式:
<script src="http://api.map.baidu.com/api?v=2.0&ak=您的密鑰" type="text/javascript"></script>
- 異步加載
JavaScript API支持異步加載,您可以在引用腳本的時(shí)候添加callback參數(shù),當(dāng)腳本加載完成后callback函數(shù)會(huì)被立刻調(diào)用。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>異步加載</title>
<script type="text/javascript">
function initialize() {
var mp = new BMap.Map('map');
mp.centerAndZoom(new BMap.Point(121.491, 31.233), 11);
}
function loadScript() {
var script = document.createElement("script");
script.src = "http://api.map.baidu.com/api?v=2.0&ak=您的密鑰&callback=initialize";//此為v2.0版本的引用方式
// http://api.map.baidu.com/api?v=1.4&ak=您的密鑰&callback=initialize"; //此為v1.4版本及以前版本的引用方式
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
</head>
<body>
<div id="map" style="width:500px;height:320px"></div>
</body>
</html>
##### 3.地圖初始化
* 創(chuàng)建地圖容器元素:
<div id="container"></div>
* 創(chuàng)建地圖實(shí)例
var map = new BMap.Map("container");
* 創(chuàng)建點(diǎn)坐標(biāo)
var point = new BMap.Point(116.404, 39.915);
* 地圖初始化
map.centerAndZoom(point, 15);
BMap.Map.centerAndZoom()方法要求設(shè)置中心點(diǎn)坐標(biāo)和地圖級(jí)別。
完整示例代碼:
<!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" />
<title>Hello,World</title>
<style type="text/css">
html{height:100%}
body{height:100%;margin:0px;padding:0px}
#container{height:100%}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的密鑰">
//v2.0版本的引用方式:src="http://api.map.baidu.com/api?v=2.0&ak=您的密鑰"
//v1.4版本及以前版本的引用方式:src="http://api.map.baidu.com/api?v=1.4&key=您的密鑰&callback=initialize"
</script>
</head>
<body>
<div id="container"></div>
<script type="text/javascript">
var map = new BMap.Map("container"); // 創(chuàng)建地圖實(shí)例
var point = new BMap.Point(116.404, 39.915); // 創(chuàng)建點(diǎn)坐標(biāo)
map.centerAndZoom(point, 15); // 初始化地圖,設(shè)置中心點(diǎn)坐標(biāo)和地圖級(jí)別
</script>
</body>
</html>
地圖經(jīng)過初始化后即可執(zhí)行其他操作。
更詳細(xì)內(nèi)容可參考:
http://lbsyun.baidu.com/index.php?title=jspopular/guide/helloworld