forked from liusaint/baiduMap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zoom.html
100 lines (87 loc) · 3.15 KB
/
zoom.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<!DOCTYPE html>
<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.5&ak=YWdGplhYjUGQ3GtpKNeuTM2S"></script>
</head>
<body>
<style type="text/css">
html{height:100%}
body{height:100%;margin:0;padding:0px}
#container{height:100%;margin: 20px;}
.info_ul{
margin:0 0 5px 0;
padding:0.2em 0;
}
.info_li{
line-height: 26px;font-size: 15px;
}
.info_span{
width: 50px;display: inline-block;
}
</style>
<div id="container"></div>
<script type="text/javascript">
//数据准备
var points = [
{"lng":116,"lat":40,"status":1,"id":50},
{"lng":117,"lat":31,"status":1,"id":2},
{"lng":116,"lat":34,"status":0,"id":3},
{"lng":118,"lat":39,"status":0,"id":4},
{"lng":110,"lat":35,"status":1,"id":5}
];
var map = new BMap.Map("container");//初始化地图
setZoom(points);//设置中心点和缩放级别。
addMarker(points);//把原始数据的轨迹点添加到地图上。
map.enableScrollWheelZoom();//滚轮放大缩小
//下面是用到的函数
//根据原始数据计算中心坐标和缩放级别,并为地图设置中心坐标和缩放级别。
function setZoom(points){
if(points.length>0){
var maxLng = points[0].lng;
var minLng = points[0].lng;
var maxLat = points[0].lat;
var minLat = points[0].lat;
var res;
for (var i = points.length - 1; i >= 0; i--) {
res = points[i];
if(res.lng > maxLng) maxLng =res.lng;
if(res.lng < minLng) minLng =res.lng;
if(res.lat > maxLat) maxLat =res.lat;
if(res.lat < minLat) minLat =res.lat;
};
var cenLng =(parseFloat(maxLng)+parseFloat(minLng))/2;
var cenLat = (parseFloat(maxLat)+parseFloat(minLat))/2;
var zoom = getZoom(maxLng, minLng, maxLat, minLat);
map.centerAndZoom(new BMap.Point(cenLng,cenLat), zoom);
}else{
//没有坐标,显示全中国。
map.centerAndZoom(new BMap.Point(103.388611,35.563611), 5);
}
}
//根据经纬极值计算绽放级别。本例核心代码。
function getZoom (maxLng, minLng, maxLat, minLat) {
var zoom = ["50","100","200","500","1000","2000","5000","10000","20000","25000","50000","100000","200000","500000","1000000","2000000"]//级别18到3。
var pointA = new BMap.Point(maxLng,maxLat); // 创建点坐标A
var pointB = new BMap.Point(minLng,minLat); // 创建点坐标B
var distance = map.getDistance(pointA,pointB).toFixed(1); //获取两点距离,保留小数点后1位
for (var i = 0,zoomLen = zoom.length; i < zoomLen; i++) {
if(zoom[i] - distance > 0){
return 18-i+3;//之所以会多3,是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
}
};
}
//在轨迹点上创建图标,并添加点击事件
function addMarker(points){
var point,marker;
// 创建标注对象并添加到地图
for(var i = 0,pointsLen = points.length;i <pointsLen;i++){
point = new BMap.Point(points[i].lng,points[i].lat);
marker = new BMap.Marker(point);
map.addOverlay(marker);
}
}
</script>
</body>
</html>