一、创建地图
建立一个htm文件,把基本的地图程序拷贝进去。最基础的地图示例。
var map = new BMap.Map("container"); //地图容器
二、创建点数组
随意创建7个点,放到一个数组里。
var points = [ //创建7个点
new BMap.Point(116.401801,39.912114),
new BMap.Point(116.402802,39.912225),
new BMap.Point(116.403803,39.912336),
new BMap.Point(116.404804,39.912447),
new BMap.Point(116.405805,39.912558),
new BMap.Point(116.406806,39.912669),
new BMap.Point(116.407804,39.912123)
];
三、创建标注
var marker1 = new BMap.Marker(points[0]); //创建7个标注
var marker2 = new BMap.Marker(points[1]);
var marker3 = new BMap.Marker(points[2]);
var marker4 = new BMap.Marker(points[3]);
var marker5 = new BMap.Marker(points[4]);
var marker6 = new BMap.Marker(points[5]);
var marker7 = new BMap.Marker(points[6]);
四、显示标注
map.addOverlay(marker1); //显示7个标注
map.addOverlay(marker2);
map.addOverlay(marker3);
map.addOverlay(marker4);
map.addOverlay(marker5);
map.addOverlay(marker6);
map.addOverlay(marker7);
五、初始化地图
map.centerAndZoom(points[6], 16); // 初始化地图,设置中心点坐标和地图级别
map.addControl(new BMap.NavigationControl()); //为地图添加鱼骨
六、让标注显示在最佳视野内
为其中一个marker添加点击事件,让这7个标注显示在最佳视野内。
marker7.addEventListener("click",function(){ //为marker7添加事件
map.setViewport(points);
});
最终效果如下图:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>自动调整视野</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2"></script>
</head>
<body>
<div style="width:800px;height:400px;border:1px solid gray" id="container"></div>
</body>
</html>
<script type="text/javascript">
var map = new BMap.Map("container"); //地图容器
var points = [ //创建7个点
new BMap.Point(116.401801,39.912114),
new BMap.Point(116.402802,39.912225),
new BMap.Point(116.403803,39.912336),
new BMap.Point(116.404804,39.912447),
new BMap.Point(116.405805,39.912558),
new BMap.Point(116.406806,39.912669),
new BMap.Point(116.407804,39.912123)
];
var marker1 = new BMap.Marker(points[0]); //创建7个标注
var marker2 = new BMap.Marker(points[1]);
var marker3 = new BMap.Marker(points[2]);
var marker4 = new BMap.Marker(points[3]);
var marker5 = new BMap.Marker(points[4]);
var marker6 = new BMap.Marker(points[5]);
var marker7 = new BMap.Marker(points[6]);
map.addOverlay(marker1); //显示7个标注
map.addOverlay(marker2);
map.addOverlay(marker3);
map.addOverlay(marker4);
map.addOverlay(marker5);
map.addOverlay(marker6);
map.addOverlay(marker7);
map.centerAndZoom(points[6], 16); // 初始化地图,设置中心点坐标和地图级别
map.addControl(new BMap.NavigationControl()); //为地图添加鱼骨
var label = new BMap.Label("点击这个标注,展现7个标注的最佳视野",{position : points[6], offset: new BMap.Size(3,-6)}); //定义一个文字标签,注意1.2请用position
map.addOverlay(label);
marker7.addEventListener("click",function(){ //为marker7添加事件
map.setViewport(points);
});
</script>