1. 程式人生 > >百度地圖 多軌跡 示例

百度地圖 多軌跡 示例

最近專案需要接百度地圖,就研究了下熱力圖和軌跡圖。

做的過程中發現軌跡圖的資料非常少,特別是多軌跡的。現在我弄出來了就分享下多軌跡的寫法,希望大家少走彎路:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<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=9LW9kU9jKiN1lDg8dClq8MRoMjURC0Es">
	
</script>
</head>


<body>
	<div id="container"></div>
	<script type="text/javascript">
	
		/* 建立地圖並新增控制元件begin */
		var map = new BMap.Map("container");
		map.centerAndZoom(new BMap.Point(121.421, 29.326), 13);
		map.addControl(new BMap.NavigationControl());
		map.addControl(new BMap.ScaleControl());
		map.addControl(new BMap.OverviewMapControl());
		map.addControl(new BMap.MapTypeControl());
		map.setCurrentCity("北京");
		/* 建立地圖並新增控制元件end  */


		/** 三組示例座標begin */
		var points = [ [ 121.42108474805796, 29.38674132050806 ],
				[ 121.42098523703464, 29.346739501953575 ],
				[ 121.43128777833854, 29.350523790258323 ],
				[ 121.42018950170755, 29.225924439068476 ] ];
		showPolyLine(points, "red");


		var points = [ [ 121.41108474805796, 29.32674132050806 ],
				[ 121.42098523703464, 29.326739501953575 ],
				[ 121.43128777833854, 29.310523790258323 ],
				[ 121.45018950170755, 29.3825924439068476 ] ];
		showPolyLine(points, "blue");


		var points = [ [ 121.51508474805796, 29.32674132050806 ],
				[ 121.42798523703464, 29.328739501953575 ],
				[ 121.43328777833854, 29.314523790258323 ],
				[ 121.45718950170755, 29.327924439068476 ] ];
		showPolyLine(points, "green")
		/* 三組示例座標begin */


		function showPolyLine(points, color) {
			/* points[][]資料結構為二維陣列,這裡轉換為Marker,再將多個marker點放入pline,組成一條線  begin */
			var pLine = [];
			for (var i = 0; i < points.length; i++) {
				pLine.push(new BMap.Point(points[i][0], points[i][1]));
				if (i == 0 || i == points.length - 1) {//起點終點圖示
					map.addOverlay(new BMap.Marker(new BMap.Point(points[i][0],
							points[i][1])));
				}
			}
			/* points[][]資料結構為二維陣列,這裡轉換為Marker,再將多個marker點放入pline,組成一條線  end */


			/* 新增軌跡介面begin */
			var polyline = new BMap.Polyline(pLine, {
				strokeColor : color,
				strokeWeight : 6,
				strokeOpacity : 0.5
			});
			map.addOverlay(polyline);
			/* 新增軌跡介面begin */
			
		};
	</script>
</body>
</html>
很簡單的示例,這是執行效果:

實際專案上用時,把座標轉成陣列傳到頁面就行了。