
第4回 地図アプリを作ってみよう! (後編)
第3回 地図アプリを作ってみよう! (前編)に引き続き、「経路の検索」と「進捗の表示」の機能をアルゴリズムと共に作っていきます。
経路の検索
最短経路を検索する
最短経路の検索には、directionsService#routeを使用しました。
サーバーに送信する検索条件(request)を設定し、directionsService#routeの引数として実行することで最短経路を検索できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var request = { origin: "福岡", destination: "博多", travelMode: google.maps.DirectionsTravelMode.WALKING, unitSystem: google.maps.DirectionsUnitSystem.METRIC, optimizeWaypoints: true, avoidHighways: false, avoidTolls: false }; directionsService.route(request, function(response,status){ if (status == google.maps.DirectionsStatus.OK){ directionsDisplay.setDirections(response);} } ); |
最短経路を検索するソースコード全体は、下記のようになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>最短経路の検索</title> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> rendererOptions = { draggable: true, preserveViewport:false }; var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions); var directionsService = new google.maps.DirectionsService(); var map; function getRoute() { var option = { zoom:16, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map (document.getElementById("map_canvas"),option); directionsDisplay.setMap(map); google.maps.event.addListener(directionsDisplay, 'directions_changed', function(){ }); var request = { origin: "福岡", destination: "博多", travelMode: google.maps.DirectionsTravelMode.WALKING, unitSystem: google.maps.DirectionsUnitSystem.METRIC, optimizeWaypoints: true, avoidHighways: false, avoidTolls: false }; directionsService.route(request, function(response,status){ if (status == google.maps.DirectionsStatus.OK){ directionsDisplay.setDirections(response);} }); } </script> </head> <body onload="getRoute()"> <p>最短経路の検索</p> <div id="map_canvas" style="width:500px; height:300px"></div> </body> </html> |
Monacaデバッガアプリを起動すると、最短経路の検索結果が表示されました。

きつい道も選べるようにする
経路の「きつさ」をどのように評価するかがポイントですが、最初はシンプルに以下のアルゴリズムで考えました。
- スタート地点とゴール地点の座標を取得
- スタート地点とゴール地点の間に4つ通過点を設定して2つの迂回路を設定
- 3つのルートを表示して経路を選択できるようにする
しかし、これでは距離のみで「きつさ」を評価しているため、正確でありません。そこで、標高を基準に通過点を抽出する以下のアルゴリズムに変更しました。
- スタート地点とゴール地点の座標を取得
- その周辺の座標の標高を取得
- 取得した標高の中から高い順、低い順にそれぞれ5つ抽出
- そのうちの4つを通過点として選択
- 「最短」、「高い」、「低い」の3つのルートから選択できるようにする
このアルゴリズムに関する処理とソースコードについては、次回説明したいと思います。
進捗の表示
経路画面に現在地を表示する
第3回 地図アプリを作ってみよう! (前編)で紹介した「現在地の表示」機能を使って、経路画面に現在地を表示します。処理とコードの説明は第3回を参照してください。
次回は……
今回は、「経路の検索」と「進捗の表示」を、アルゴリズムと共に作成しました。次回は、これまで紹介した機能を使って地図アプリを完成させていきたいと思います。