カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

GoogleMap ルート検索

この記事は最終更新日から1年以上経過しています。

GoogleのGoogleMap APIを使ってルート検索をすることができます。

まず、ルート検索のプロパティを指定します。

// Route Request Property
var request = {
    origin: null,            // 出発地点のLatLngオブジェクト
    destination: null,       // 到着地点のLatLngオブジェクト
    travelMode: google.maps.DirectionsTravelMode.DRIVING,
    avoidHighways: true, // true に設定すると、高速道路を可能な限りルートの計算から除外するように指定されます。(省略可能)
    avoidTolls: true     // true に設定すると、有料道路を可能な限りルートの計算から除外するように指定されます。(省略可能)
};

トラベルモードについては

DRIVING=自動車
BICYCLING=自転車
TRANSIT=電車
WALKING=徒歩

出発地点と到着地点を設定します。

request.origin      = new google.maps.LatLng(34.73307796637832, 135.49859046936035);  //新大阪駅
request.destination = new google.maps.LatLng(35.681003987351055, 139.76703643798828); //東京駅

DirectionsServiceのインスタンスを生成

var directionsService = new google.maps.DirectionsService();

ルート表示のオブジェクトを作成し、プロパティを設定します。
ここではGoogleMapオブジェクト、「map」は作成済とします。

directionsDisplay = new google.maps.DirectionsRenderer({
    "map": map,
    "preserveViewport": true, // ルート全体を表示せず、指定した座標とズームレベルで表示させたい場合にtrue
    "draggable": true         // 経路をドラッグで変更の可/不可
});

実際にルート検索を実行します。
返ってきたレスポンスを、先程作成した表示用のオブジェクトに渡します。

directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
    }
});

【経由地を設定する場合】

経由地の配列を作成します。

myWaypoints = [];
myWaypoints.push( {
    location: new google.maps.LatLng(35.65535197094431, 139.7486392810783),
    stopover: true // このウェイポイントが実際の停止地点であるのか(true)、経由を希望しているだけなのか(false)を指定します。デフォルト:true
    });
myWaypoints.push( {
    location: new google.maps.LatLng(35.629313313361514, 139.88454606758023)
    });

ルート検索のプロパティを以下のように設定

// Route Request Property
var request = {
    waypoints: myWaypoints,  // 経由地点の配列(最大8か所)
    optimizeWaypoints: true, // 経由地点最適化の有無
    origin: null,            // 出発地点のLatLngオブジェクト
    destination: null,       // 到着地点のLatLngオブジェクト
    travelMode: google.maps.DirectionsTravelMode.DRIVING,
    avoidHighways: true,
    avoidTolls: true
};

参考URL
https://developers.google.com/maps/documentation/javascript/directions?hl=ja

この記事がお役に立ちましたらシェアお願いします
5,822 views

コメントを残す

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