AdSense

網頁

2026/1/12

Java Google Map Platform Routes API簡單範例

Java程式呼叫Google Map Platform Routes API的簡單範例


Routes API主要用來獲取地圖上兩點的路徑資訊,提供有Compute RoutesCompute Routes Matrix兩個方法(API)。

Routes API和舊的(legacy)Directions APIDistance Matrix API功能類似,但多了一些其他特色。


事前要求

需要有Google Cloud Platform(GCP)帳號,並啟用Routes API,取得API金鑰(API key)。


範例

下面範例呼叫Routes API的Compute Routes方法(API文件參考),呼叫POST https://routes.googleapis.com/directions/v2:computeRoutes

在請求頭設定以下。

  • X-Goog-Api-Key=API_KEY - 為API金鑰
  • X-Goog-FieldMask=routes.distanceMeters,routes.duration - 為回傳欄位遮罩,用來指示要回應那些欄位,若未填寫會發生錯誤。這邊指定回傳距離(routes.distanceMeters)和時間(routes.duration)。

請求主體

  • origin.address - 出發地的地址。
  • destination.address - 目的地的地址。
  • travelMode - 移動方式
    • TRAVEL_MODE_UNSPECIFIED - 不指定
    • DRIVE - 汽車
    • BICYCLE - 單車/腳踏車
    • WALK - 走路/步行
    • TWO_WHEELER - 機車/摩托車
    • TRANSIT - 大眾運輸


package com.abc.demo;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class MyApp {

    public static void main(String[] args) throws Exception {
        String apiKey = "API_KEY";

        String requestBody = new ObjectMapper().writeValueAsString(Map.of(
                "origin", Map.of("address", "桃園市桃園區大同路100號"),
                "destination", Map.of("address", "台北市內湖區瑞光路515號"),
                "travelMode", "TWO_WHEELER"));

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://routes.googleapis.com/directions/v2:computeRoutes"))
                .header("Content-Type", "application/json")
                .header("X-Goog-Api-Key", apiKey)
                .header("X-Goog-FieldMask", String.join(",",
                        "routes.distanceMeters",
                        "routes.duration"))
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response;

        response = client.send(request, HttpResponse.BodyHandlers.ofString());
        String responseBody = response.body();
        System.out.println("Response Body: " + responseBody);

    }

}

github



測試

執行印出以下:

Response Body: {
  "routes": [
    {
      "distanceMeters": 37888,
      "duration": "4154s",
      "staticDuration": "4154s"
    }
  ]
}

沒有留言:

AdSense