「GoogleMaps API V3」 の使い方その10(ルート検索2)
■ルート検索の結果をルートレンダラで表示
「その9」の例では、ポリラインを使ってルート検索結果を描画しましたが、ルートレンダラを使えばそんな面倒なことはしなくても簡単に描画することができます。
ルートとルートレンダラのインスタンスをマップの生成と共に、初期処理にて生成しておきます。
[検索]ボタンをクリックされた時に、ルートの route メソッドを利用してルートのリクエストを行います。
ルート検索の結果は route メソッドで宣言された、コールバック関数に帰ってきます。
コールバック関数は results, status の引数を持ち、statusがOKでなければエラーが発生しています。
statusがOKの場合、ルートレンダラの setDirections メソッドにresultsを渡すことで、ルートが描画されます。
results[0]のプロパティとして overview_path がありますが、緯度・経度の配列として格納されています。
02 | <title>Google Map API v3-10</title> |
03 | <script type= "text/javascript" src= "http://maps.google.com/maps/api/js?key=MyKeyCode" charset= "utf-8" ></script> |
04 | <script type= "text/javascript" > |
08 | var ds = google.maps.DirectionsStatus; |
09 | var directionsErr = new Array(); |
10 | directionsErr[ds.INVALID_REQUEST] = "指定された DirectionsRequest が無効です。" ; |
11 | directionsErr[ds.MAX_WAYPOINTS_EXCEEDED] = "DirectionsRequest に指定された DirectionsWaypoint が多すぎます。ウェイポイントの最大許容数は 8 に出発地点と到着地点を加えた数です。" ; |
12 | directionsErr[ds.NOT_FOUND] = "出発地点、到着地点、ウェイポイントのうち、少なくとも 1 つがジオコード化できませんでした。" ; |
13 | directionsErr[ds.OVER_QUERY_LIMIT] = "ウェブページは、短期間にリクエストの制限回数を超えました。" ; |
14 | directionsErr[ds.REQUEST_DENIED] = "ウェブページではルート サービスを使用できません。" ; |
15 | directionsErr[ds.UNKNOWN_ERROR] = "サーバー エラーのため、ルート リクエストを処理できませんでした。もう一度試すと正常に処理される可能性があります。" ; |
16 | directionsErr[ds.ZERO_RESULTS] = "出発地点と到着地点間でルートを見つけられませんでした。" ; |
19 | function initialize() { |
21 | directions = new google.maps.DirectionsService(); |
23 | directionRenderer = new google.maps.DirectionsRenderer(); |
27 | mapTypeId: google.maps.MapTypeId.ROADMAP, |
28 | center: new google.maps.LatLng(36.062092, 136.223323) |
31 | map = new google.maps.Map(document.getElementById( "map" ), mapOptions); |
33 | directionRenderer.setMap(map); |
36 | function searchRoute() { |
38 | var origin = document.getElementById( "origin" ).value; |
39 | var destination = document.getElementById( "destination" ).value; |
44 | 'destination' : destination, |
45 | 'travelMode' : google.maps.DirectionsTravelMode.WALKING |
47 | function (results, status) { |
48 | if (status == ds.OK) { |
50 | directionRenderer.setDirections(results); |
53 | alert( "ルート検索が失敗しました。理由: " + directionsErr[status]); |
59 | <body onload= "initialize();" > |
60 | <div id= "map" style= "width: 520px; height: 400px;" ></div> |
62 | <input id= "origin" type= "textbox" value= "福井駅(福井)" size= "40" ><br /> |
63 | <input id= "destination" type= "textbox" value= "福井県福井市役所" size= "40" ><br /> |
64 | <input type= "button" value= "検索" onclick= "searchRoute()" > |
■関連記事
⇒
「GoogleMaps API V3」の使い方その1
⇒
「GoogleMaps API V3」の使い方その2
⇒
「GoogleMaps API V3」の使い方その3(マーカーの表示)
⇒
「GoogleMaps API V3」の使い方その4(イベント)
⇒
「GoogleMaps API V3」の使い方その5(続イベント)
⇒
「GoogleMaps API V3」の使い方その6(続々イベント)
⇒
「GoogleMaps API V3」の使い方その7(ポリライン・ポリゴン)
⇒
「GoogleMaps API V3」の使い方その8(ジオコーディング)
⇒
「GoogleMaps API V3」の使い方その9(ルート検索)
⇒
「GoogleMaps API V3」の使い方その11(さらにInfowindow)