本篇將向各位介紹 Google Maps JavaScript API 第 3 版,以下內容皆由 Google 開發者文件以及往年投影片(2012, 2013) (by Ronald Hsu)修改而來。

以下是一個基礎範例:

<!DOCTYPE html>
<html>
<head>
	<style type="text/css">
		/* 清除預設樣式,使地圖佔滿畫面 */
		html{height:100%}
		body{height:100%;margin:0;padding:0}
		#map_canvas{height:100%}
	</style>
	
	<!--載入 API-->
	<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
	
	<script type="text/javascript">
		function initialize() {
			var mapOptions = {
				center: new google.maps.LatLng(24.8, 120.97),
				zoom: 10,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
		}
	</script>
</head>
<body onload="initialize()">

<div id="map_canvas" style="width:100%; height:100%"></div>

</body></html>

其中在載入 API 時的「sensor=false」,代表瀏覽器沒有使用 GPS 等感應器來探測使用者的位置。而用到的地圖選項參數意義則如下:

如果要透過 Google,依據 IP 幫你自動取得地理位置,在比較早期的版本,是使用 google.loader.ClientLocation 來進行:

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="http://www.google.com/jsapi"></script>
	
	<script type="text/javascript">
		google.load("maps", "3",  {callback: initialize, other_params:"sensor=false"});
		
		function initialize() {
			var zoom = 10;
			var latlng = new google.maps.LatLng(23.5, 120.0);
			
			if (google.loader.ClientLocation) {
				latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude,
												google.loader.ClientLocation.longitude);
			}
		
			var mapOptions = {
				center: latlng,
				zoom: zoom,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
		}
	</script>
</head>
<body>

<div id="map_canvas" style="width:800px;height:500px"></div>

</body></html>

而在 HTML5 當中,則新增了定位功能,主要是使用 geolocation.getCurrentPosition,如下:

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
	
	<script type="text/javascript">
		navigator.geolocation.getCurrentPosition(initialize);
		
		function initialize(position) {
			var zoom = 10;
			 latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
		
			var mapOptions = {
				center: latlng,
				zoom: zoom,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
		}
	</script>
</head>
<body>

<div id="map_canvas" style="width:800px;height:500px"></div>

</body></html>

藉由「google.maps.Marker」物件,可以在圖上進行標記。範例中,一開始已存在一個 marker,按鈕後,再將其他 markers 加到地圖上:

<!DOCTYPE html>
<html>
<head>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
	
	<script type="text/javascript">
		var neighborhoods = [
			new google.maps.LatLng(24.983, 121.3), // lamigo
			new google.maps.LatLng(23+8/60, 120+17/60), // lion
			new google.maps.LatLng(22+38/60, 120+17/60), // rhino
		];
		
		var markers = [];
		var iterator = 0;
		var map;
	  
		function initialize() {
			var mapOptions = {
				center: new google.maps.LatLng(24.8, 120.97),
				zoom: 7,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			
			map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
			
			var marker = new google.maps.Marker({ /* 一開始就有的 marker */
				position: new google.maps.LatLng(25.05, 121.5),
				map: map,
				title: '天龍國!!'
			});
		}
		
		function dropdrop(){
			for(var i=0;i<neighborhoods.length;i++){
				setTimeout("addMarker();", i*200);
			}
		}
		
		function addMarker(){
			markers.push(
				new google.maps.Marker({
					position: neighborhoods[iterator],
					map: map, /* 丟到哪張地圖上 */
					draggable: false, /* 可否拖放 */
					animation: google.maps.Animation.DROP, /* 動畫設定 */
					icon: '../pics/elephant.png', /* 可以自訂 marker 圖案 */
					title: '南部!!'
				})
			);
			iterator++;
		}
	</script>
</head>
<body onload="initialize()">

<div id="map_canvas" style="width:800px; height:600px"></div>
<input type="button" value="新增markers" onclick="dropdrop()">

</body></html>

藉由「google.maps.event.addListener」方法,可以監聽在圖上發生的事件。此範例中,如果你在地圖上按滑鼠左鍵,則會將 marker 定位在按下左鍵的位置:

<!DOCTYPE html>
<html>
<head>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

	<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
	<script type="text/javascript" src="http://www.google.com/jsapi"></script>
	
	<script type="text/javascript">
		
		function initialize() {
			var zoom = 10;
			var latlng = new google.maps.LatLng(23.5, 120.0);
			var markers = [];
			
			if (google.loader.ClientLocation) {
				latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude,
												google.loader.ClientLocation.longitude);
			}
		
			var mapOptions = {
				center: latlng,
				zoom: zoom,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
			
			/* 在地圖綁上 onclick 事件,藉以處理 marker 的動作 */
			google.maps.event.addListener(
				map,
				'click',
				function(e) {
					userMarker.setPosition(e.latLng);
					/** // 如果要每點一下就有一個 marker,則使用此段
					markers.push(
						new google.maps.Marker({
							position: e.latLng,
							map: map,
							draggable: false,
							animation: google.maps.Animation.DROP,
							icon: '../pics/elephant.png'
						})
					);
					**/
				}
			);

			var userMarker = new google.maps.Marker({
				map: map,
				//position: latlng, // 如果需要一開始就有marker,可以打開此行
				icon: "../pics/elephant.png"
			});
		} /* end function */
	</script>
</head>
<body onload="initialize()">

<div id="map_canvas" style="width:800px; height:600px"></div>

</body></html>

GeoCoder 可用來搜尋地址,定位出座標:

<!DOCTYPE html>
<html>
<head>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
	
	<script type="text/javascript">
		var geocoder, map, zoom = 15;
		
		function initialize() {
			geocoder = new google.maps.Geocoder();
			var latlng = new google.maps.LatLng(23.5, 120.5);
			var markers = [];
		
			var mapOptions = {
				center: latlng,
				zoom: zoom,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
		}
		
		function codeAddress(){
			var address = document.getElementById('address').value;
			geocoder.geocode(
				{'address': address} ,
				function(results, status){ /* 查詢完成時執行的函式 */
					if(status == google.maps.GeocoderStatus.OK) {
						map.setCenter(results[0].geometry.location);
						map.setZoom(zoom);
						var marker = new google.maps.Marker({
							map: map,
							position: results[0].geometry.location
						});
					}
					else {
						alert('Geocode was not successful for the following reason: ' + status);
					}
				}
			);
		}
	</script>
</head>
<body onload="initialize()">

<input id="address" type="textbox" value="新竹市光復路二段101號 ">
<input type="button" value="Geocode" onclick="codeAddress()">

<div id="map_canvas" style="width:800px; height:600px"></div>

</body></html>

Route 可以用來規畫行程。此範例中,點第一下和第二下各會新增一個 marker;之後,你可以拖動 marker,來產生與改變行程規畫:

<!DOCTYPE html>
<html>
<head>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
	<script type="text/javascript">
		var map;
		var zoom = 15;
		var markers = [];
		var directionDisplay;
		var directionsService = new google.maps.DirectionsService()
		
		function initialize() {
			directionsDisplay = new google.maps.DirectionsRenderer();
			var latlng = new google.maps.LatLng(23.5, 120.5);
		
			var mapOptions = {
				center: latlng,
				zoom: zoom,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
			directionsDisplay.setMap(map);
			
			google.maps.event.addListener(map, 'click',
				function(e) {
					/* 如果還沒加滿兩個 markers */
					if(markers.length<2){
						/* 加上新 marker */
						markers.push(
							new google.maps.Marker({
								position: e.latLng,
								map: map,
								draggable: true
							})
						);
						/* 綁上 dragend 事件,拖放結束時重新計算路徑 */
						google.maps.event.addListener(markers[markers.length-1], 'dragend',
							function(e){
								calcRoute();
							}
						);
					}
				}
			);
		}
		
		function calcRoute(){
			/* 設定規劃路線的參數 */
			var request = {
				origin: markers[0].getPosition(),
				destination: markers[1].getPosition(),
				travelMode: google.maps.DirectionsTravelMode.DRIVING
			};
			directionsService.route(request,
				function(response, status) {
					if (status == google.maps.DirectionsStatus.OK) {
						directionsDisplay.setDirections(response);
					}
				}
			);
		}
	</script>
</head>
<body onload="initialize()">

<div id="map_canvas" style="width:800px; height:600px"></div>

</body></html>

其餘的 API 範例,可以參考以下連結,此處不再贅述。

另外若有興趣,也可以參考研究網路上的知名範例,例如:迪歐版::實價登錄地圖,以及 制服地圖等等。