指定した2点間のルート検索を行う

説明

指定した2点間のルート検索を行うにはnew google.maps.DirectionsRenderer()を使ってルート検索の結果を表示するためのオブジェクトを生成します。new google.maps.Map()により生成したマップオブジェクトをDirectionsRendererオブジェクトのsetMap()を使って関連付けます。
次にルート検索を行うサービスを処理するオブジェクトをnew google.maps.DirectionsService()を使って生成します。作成されたオブジェクトのroute()を使ってルート検索を実行します。route()のオプションパラメータのoriginに出発地をdestinationに到着地点を指定します。英語でなく日本語で出発地や目的地を指定できます。travelModeで電車か自動車かなどを指定できます。これは以下のものを指定できます。

google.maps.DirectionsTravelMode.DRIVING自動車でのルート
google.maps.DirectionsTravelMode.WALKING徒歩でのルート
google.maps.DirectionsTravelMode.BICYCLING自転車でのルート

route()メソッドの2番目のパラメータにルート検索が行われた際に結果を受け取るための関数(イベントハンドラ)を指定します。この関数には2つのパラメータが渡されます。最初のパラメータが結果、2番目のパラメータがステータスになります。ステータスの結果がOKであればルート検索に成功した事になります。成功した場合にはdirectionsDisplay.setDirections(response)としてルートをマップ上に表示します。
失敗した場合にはエラーメッセージ等を表示します。ルート検索で返されるステータスには以下のものがあります。

google.maps.DirectionsStatus.OKOK。ルート検索に成功
google.maps.DirectionsStatus.INVALID_REQUESTリクエストが無効
google.maps.DirectionsStatus.MAX_WAYPOINTS_EXCEEDEDウェイポイント(経由地点)が8を超えた
google.maps.DirectionsStatus.NOT_FOUND出発地か到着のジオコードに失敗(場所が見つからない)
google.maps.DirectionsStatus.OVER_QUERY_LIMITリクエストの制限回数を超えた
google.maps.DirectionsStatus.REQUEST_DENIEDルート検索は使えない
google.maps.DirectionsStatus.ZERO_RESULTSルートが見つかりません
google.maps.DirectionsStatus.UNKNOWN_ERRORサーバーエラー。リトライすれば成功する可能性あり

Google Maps APIプログラミング入門 Google Maps API プログラミング入門。Google Maps API Expertである勝又雅史氏が最新のAPI ver3やGoogle Maps for Flashなどについて解説しています。
アマゾンで購入する

サンプルコード [実行]

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Google Maps API ver 3 Sample/グーグルマップAPIサンプル/Google Maps API样品</title>
<link rel="stylesheet" href="css/main.css" type="text/css" media="all">
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
<div id="gmap"></div>
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(
document.getElementById("gmap"),{
zoom : 8,
center : new google.maps.LatLng(35.689160610317174, 139.70083951950073),
mapTypeId : google.maps.MapTypeId.ROADMAP
}
);
directionsDisplay.setMap(map);
directionsService.route({
origin : "新宿駅",
destination: "塩尻駅",
travelMode: google.maps.DirectionsTravelMode.DRIVING
},function(response, status){
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}else{
alert("ルート検索に失敗しました");
}
});
</script>
</body>
</html>