[Google Map]畫線(GPolyline)

八月 9, 2008

除了用 mark 在地圖上標出座標外,我們還能在地圖上畫線表示路線等資訊。


Google API

  • GPolyline : This is a map overlay that draws a polyline on the map, using the vector drawing facilities of the browser if they are available, or an image overlay from Google servers otherwise.

程式碼

執行範例:取得目前地圖的可視範圍,隨機加入10個標籤,並畫線

google.load("maps", "2.x");
google.setOnLoadCallback(initialize);

var map = null;
function initialize() {
	// 檢查瀏覽器是否可使用 Google Map API
	if ( GBrowserIsCompatible() ) {
        map = new google.maps.Map2(document.getElementById('map'));
		// 設定地圖中心點
		map.setCenter(new GLatLng(25.036772,121.520269), 12);
		
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest(); // 返回矩形西南角的點
		var northEast = bounds.getNorthEast(); // 返回矩形東北角的點
		var lngSpan = northEast.lng() - southWest.lng();
		var latSpan = northEast.lat() - southWest.lat();
		var points = [];
		// 亂數取點
		for (var i = 0; i < 10; i++){
		    var point = new GLatLng(
		        southWest.lat() + latSpan * Math.random(),
		        southWest.lng() + lngSpan * Math.random());
		    points.push(point);
		    map.addOverlay(new GMarker(point));
		} // for
		// 排序
		points.sort(function(p1, p2) { return p1.lng() - p2.lng();});
		// 畫線!
		map.addOverlay(new GPolyline(points));
	} // if
	else {
		alert('您的瀏覽器不支援Google Map');
	} // else
}

Comments are closed.