Google Maps API - 路線規劃

使用 Google 地圖時,「路線規劃」便是其中一個常用的情境,一個完整的路線規劃,不僅包含了如何抵達,更具備行走、腳踏車或大眾運輸...等指示功能,這篇文章將會透過 Directions API 實作具備 Google 地圖路線規劃的網頁。

啟用 Directions API

前往 Google Cloud Platform Console,建立新的專案或是選擇現有的專案 ( 不知道怎麼做可以參考 Google Maps API - 網頁載入地圖 ( 起手式 ) ),接著點選上方「啟用 API 和服務」。

Google Maps API - 路線規劃

在搜尋欄位搜尋「Directions API」,找到後點選並且啟用。

Google Maps API - 路線規劃

Directions 的屬性

屬性 說明
origin <必要> 起始位置,可以使用經緯度、Place ID 或地理編碼 ( 地址定位 )
destination <必要> 終點位置,可以使用經緯度、Place ID 或地理編碼 ( 地址定位 )。
travelMode <必要> 移動方式,有 DRIVING ( 開車 )、BICYCLING ( 腳踏車 )、TRANSIT ( 大眾運輸 ) 和 WALKING ( 走路 ) 四種模式,預設為 DRIVING
transitOptions 交通工具選項,有 arrivalTime/departureTime、modes ( 陣列,有 BUS、RAIL、SUBWAY 和 TRAIN )、routingPreference ( FEWER_TRANSFERS 最少轉乘數、LESS_WALKING 最少步行數 )。
drivingOptions 開車選項,有 departureTime、trafficModel ( bestguess、pessimistic、optimistic ),trafficModel 預設為 bestguess
unitSystem 距離單位系統,有 UnitSystem.METRIC ( 公里 ) 和 UnitSystem.IMPERIAL ( 英里 ) 兩個選項,預設為 UnitSystem.METRIC
waypoints[] 中途路徑點,陣列,有 location 和 stopover 選項。
optimizeWaypoints 優化並重新排序路徑點,可設定 true 或 false。
provideRouteAlternatives 提供路線選擇,可設定 true 或 false。
avoidFerries 忽略渡輪,可設定 true 或 false。
avoidHighways 忽略高速公路,可設定 true 或 false。
avoidTolls 忽略收費公路,可設定 true 或 false。
region 區域代碼,預設會直接抓取域名來判斷,以便正確顯示該區域的呈現結果。

起手式

要使用 Google Maps API 的路線規劃,開始先載入DirectionsService()DirectionsRenderer(),因為在 Google Map 裡,所有額外添加上去的都是圖層,所以透過directionsDisplay.setMap(map)設定路線規劃的圖層,再透過directionsService.route繪製。

範例:Google Maps API 的路線規劃起手式

var map;
function initMap() {}
    // 載入路線服務與路線顯示圖層
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();

    // 初始化地圖
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: { lat: 25.034010, lng: 121.562428 }
    });

    // 放置路線圖層
    directionsDisplay.setMap(map);

    // 路線相關設定
    var request = {
        origin: { lat: 25.034010, lng: 121.562428 },
        destination: { lat: 25.037906, lng: 121.549781 },
        travelMode: 'DRIVING'
    };

    // 繪製路線
    directionsService.route(request, function (result, status) {
        if (status == 'OK') {
            // 回傳路線上每個步驟的細節
            console.log(result.routes[0].legs[0].steps);
            directionsDisplay.setDirections(result);
        } else {
            console.log(status);
        }
    });
}

Google Maps API - 路線規劃

獲取路線指示內容

在上面程式碼的最後面,當繪製狀態回傳 OK 之後,我們也可使用 console 來看看每段路徑的內容細節,從裡頭能瞧見像是instructions表示路線的指示,還有路線上每個點的經緯度都看一目瞭然。

Google Maps API - 路線規劃

知道如何獲取指示之後,我們將上方的程式碼的後半段稍作改良,加入地圖標記、資訊視窗和地圖標記點擊事件,如此一來我們就能在路線的每個主要位置,加上對應的標記和指示。

範例:在路線上顯示每段路徑的指示內容

額外參考:地圖標記 ( Marker )地圖標記點擊事件資訊視窗 ( Infowindow )

var markers = [];
var infowindows = [];
// 繪製路線
directionsService.route(request, function (result, status) {
    if (status == 'OK') {
    // 回傳路線上每個步驟的細節
    var steps = result.routes[0].legs[0].steps;
    steps.forEach((e, i) => {
        console.log(steps);
        // 加入地圖標記
        markers[i] = new google.maps.Marker({
        position: { lat: e.start_location.lat(), lng: e.start_location.lng() },
        map: map,
        label: { text: i + '', color: "#fff" }
        });
        // 加入資訊視窗
        infowindows[i] = new google.maps.InfoWindow({
        content: e.instructions
        });
        // 加入地圖標記點擊事件
        markers[i].addListener('click', function () {
        if(infowindows[i].anchor){
            infowindows[i].close();
        }else{
            infowindows[i].open(map, markers[i]);
        }
        });
    });
    directionsDisplay.setDirections(result);
    } else {
    console.log(status);
    }
});

Google Maps API - 路線規劃

顯示大眾運輸路線

如果我們把travelMode: 'DRIVING'改成TRANSIT,就能夠即時顯示大眾運輸的路線,大眾運輸共有四種方式,分別是 BUS、RAIL、SUBWAY 和 TRAIN,在台灣 RAIL 和 SUBWAY 應該都是指捷運 ( 如果在高雄,RAIL 有可能會是輕軌 ),不過如果自己做測試,在沒有大眾運輸的時段裡,就不會有路線規劃顯示,使用方式如下,就是修改travelMode,並加入travelOprions的設定。( 比較需要注意的是 modes 內容為陣列 )

範例:顯示大眾運輸路線

var request = {
    origin: { lat: 25.057448, lng: 121.557726 },
    destination: { lat: 25.048067, lng: 121.517475 },
    travelMode: 'TRANSIT',
    transitOptions: {modes:['SUBWAY']}
};

Google Maps API - 路線規劃

如果改成 BUS 就會變成下圖這樣。

Google Maps API - 路線規劃

小結

總而言之,Google Maps API 在路線規劃上非常的完整,但除非是要自己做應用,不然直接開啟 Google Maps 出來使用就可以囉!我自己出國玩,查路線和大眾運輸也都是借重這個超方便的功能!之後會再找時間,把路線規劃再拿來做點好玩的應用。

有興趣瞧瞧其他新文章嗎?