AngularJSを使ってGoogleマップ(7)ルートサービスを使って簡単な徒歩ルートを表示する

ルートサービスを使って、出発地から目的地への徒歩ルートを表示させてみます。

出発地と目的地をSelectボックスで選択すると2地点間の徒歩ルートを地図上に表示するサンプルコードを作ってみます。
 
デモとコードサンプルはこちら
 

サンプルコードの説明


 
1)出発地、目的地を指定するフォーム(HTML、スクリプト)
 
①ブートストラップ3でレイアウトを設定
 
<div class=”form-group”>、<select class=”form-control”>など。
 
②AngularJSの”ng-options”を使ってselectタグとそれに紐づくoptionタグを生成
 
<select class=”form-control” ng-model=”routePoints.end”
 ng-options=”route.name for route in map.routes.end”>
</select>
 
・スクリプト内の”routes.end”配列からデータを読み出し、optionタグを生成。
 
・Selectタグで選択された値は、”routePoints.end”に保持されてスクリプトに渡される。
 
・Selectタグの初期表示される項目を設定
 
それぞれの配列の最初の値を初期表示させる。
$scope.routePoints.start = $scope.map.routes.start[0];
$scope.routePoints.end = $scope.map.routes.end[0];
 
③フォームの送信ボタンクリックで、ルート計算実行
 
<button ng-click=”calcRoute(routePoints)” type=”submit” class=”btn btn-default”>送信</button>
 
2)ルートサービスの使用方法(スクリプト)
 
①ルート計算の条件(出発地、目的地、徒歩/電車などのモード)を設定
 
フォームのSelectボックスで指定された値を取得し、ルート計算の条件を設定
 
var start = routePoints.start.latlng;
var end = routePoints.end.latlng;
var request = {
 origin: start,
 destination: end,
 travelMode: google.maps.TravelMode.WALKING
};
 
②ルートを計算
 
上記①の条件を引数に指定してDirectionsServiceオブジェクトのroute()メソッドを実行。
 
directionsService.route(request, function(response, status) {
 if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay.setDirections(response);
 }
});
 
※directionsService.routeの構文
directionsService.route(request:DirectionsRequest, callback:function(DirectionsResult, DirectionsStatus))
 
③ルートの計算結果を表示
 
上記②のdirectionsService.routeメソッドのコールバック関数内で処理。
 
ルート計算のステータスを上記コードの”status”(DirectionsStatusオブジェクト)を使って確認し、OKだったらルート結果を地図上に表示。
 
ルート計算の結果は、上記コードの”response”(DirectionsResultオブジェクト)に保持されていて、DirectionsRendererオブジェクトを使って表示。

関連記事の目次

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください