V3のマップにルート案内 (Directions API) を実装しよう。
APIで提供される交通手段は車・徒歩・自転車で、電車や飛行機を使う経路や発着時間を指定しての検索は出来ない。
なのでロサンゼルスから東京に移動するルートなんかを検索すると「太平洋をカヤックで横断する」と出たりする。
遠方の検索は公式の地図検索を使えって事なんだと思う。
解説は抜粋なのでソース全文は記事末尾からダウンロード出来るZipのjsファイルを見てください。
InfoWindowのContentをカスタマイズする
起点となるポイントに表示されるマーカーにInfoWindowを設定して、
以前使われていた「ここへ到着・ここから出発」を表示させる。
InfoWindowコンテンツのHTMLを保存しておくグローバル変数を用意する。
キーで表示するソースを切り替えるので初期値は空のオブジェクト。
var direction_html={};
他にMap、LatLng、InfoWindowを入れるグローバル変数も必要です。
コンフィグでDirectionをONにしたときだけ実行するmap_direction関数内で
InfoWindowのコンテンツに付け足すHTMLを作成する。
//他省略 direction_html["normal"] = '<div style="margin-top:0.5em">ルート案内: <a href="javascript:tohere()">ここへ到着<\/a> - <a href="javascript:fromhere()">ここから出発<\/a></div>';
HTMLを追加するかどうかはクリックされた時に判断。
InfoWindowオブジェクトを作成する時のOption.contetにHTMLソースを設定すれば、
窓がオープンしたときにその内容が表示される。
google.maps.event.addListener(marker, 'click', function() { if(infowindow) infowindow.close(); infowindow = new google.maps.InfoWindow({ content: gmConfig.iw.content +((gmConfig.directions)?direction_html.normal:"") }); infowindow.open(map,marker); });
ここへ到着/ここから出発が押された時
窓がオープンしていたらclose()で閉じる。
その後はもう一度InfoWindowを作成してOption.contentにHTMLを設定するだけ。
//ここへ到着 function tohere() { if(infowindow) infowindow.close(); infowindow = new google.maps.InfoWindow({ content: gmConfig.iw.content + direction_html.to }); infowindow.open(map,marker); }
Directions APIの設定
Documentでは小難しく書いてあるけど初期化に必要なのは次の5行。
directionDiv = document.getElementById("directions"); directionsService = new google.maps.DirectionsService(); directionsDisplay = new google.maps.DirectionsRenderer(); directionsDisplay.setMap(map); directionsDisplay.setPanel(directionDiv);
DirectionsServiceがルート計算を行うためのもので、DirectionsRendererが結果を表示するためのもの。
DirectionsRendererはsetMapでMapオブジェクトを、setPanelで表示先の要素を設定する。
ルートの検索にはDirectionsServiceのrouteメソッドを使う。
オプションで「スタート地点」「目的地」「トラベルモード」の指定が必須。
※以下は公式ドキュメントのソース
function calcRoute() { var start = document.getElementById("start").value; var end = document.getElementById("end").value; var request = { origin:start, //スタート地点 destination:end, //目的地 travelMode: google.maps.DirectionsTravelMode.DRIVING }; directionsService.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(result); } }); }
「スタート地点」と「目的地」はLatLng座標の他、地名やランドマーク名でもいい。
ユーザーに決めさせるならテキストエリアやhidden要素のvalueを得るようにして、
検索ボタンを押されるかした時にdirectionsService.route()を実行すれば経路を得ることが出来る。
返されたリクエストステータスがOKなら結果をsetPanelで指定した要素に表示します。
TravelMode Option
google.maps.DirectionsTravelMode.BICYCLING |
自転車ルート リクエストを指定 |
google.maps.DirectionsTravelMode.DRIVING |
運転ルート リクエストを指定 |
google.maps.DirectionsTravelMode.WALKING |
徒歩ルート リクエストを指定 |