|
| 1 | +/* |
| 2 | + * Copyright 2026 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.maps3djava.routes; |
| 18 | + |
| 19 | +import com.google.android.gms.maps.model.LatLng; |
| 20 | +import org.json.JSONArray; |
| 21 | +import org.json.JSONObject; |
| 22 | + |
| 23 | +import java.io.BufferedReader; |
| 24 | +import java.io.InputStreamReader; |
| 25 | +import java.io.OutputStreamWriter; |
| 26 | +import java.net.HttpURLConnection; |
| 27 | +import java.net.URL; |
| 28 | +import java.util.ArrayList; |
| 29 | +import java.util.List; |
| 30 | +import java.util.concurrent.Callable; |
| 31 | + |
| 32 | +/** |
| 33 | + * Represents the decoded route and step waypoints payload for the Java Routes API sample. |
| 34 | + */ |
| 35 | +class RouteData { |
| 36 | + private final String encodedPolyline; |
| 37 | + private final List<LatLng> navPoints; |
| 38 | + |
| 39 | + public RouteData(String encodedPolyline, List<LatLng> navPoints) { |
| 40 | + this.encodedPolyline = encodedPolyline; |
| 41 | + this.navPoints = navPoints; |
| 42 | + } |
| 43 | + |
| 44 | + public String getEncodedPolyline() { |
| 45 | + return encodedPolyline; |
| 46 | + } |
| 47 | + |
| 48 | + public List<LatLng> getNavPoints() { |
| 49 | + return navPoints; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * A data repository responsible for executing background network tasks to compute driving |
| 55 | + * directions using the Google Maps Routes API (v2) in Java. |
| 56 | + */ |
| 57 | +public class RouteRepository { |
| 58 | + |
| 59 | + /** |
| 60 | + * Returns a Callable to fetch the route in a background thread pool. |
| 61 | + * |
| 62 | + * @param apiKey The API key to authenticate client requests. |
| 63 | + * @param origin Starting coordinate. |
| 64 | + * @param destination Destination coordinate. |
| 65 | + * @return A Callable producing [RouteData]. |
| 66 | + */ |
| 67 | + public Callable<RouteData> fetchRouteCallable(String apiKey, LatLng origin, LatLng destination) { |
| 68 | + return () -> { |
| 69 | + URL url = new URL("https://routes.googleapis.com/directions/v2:computeRoutes"); |
| 70 | + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
| 71 | + connection.setRequestMethod("POST"); |
| 72 | + connection.setRequestProperty("Content-Type", "application/json"); |
| 73 | + connection.setRequestProperty("X-Goog-Api-Key", apiKey); |
| 74 | + connection.setRequestProperty("X-Goog-FieldMask", "routes.polyline.encodedPolyline,routes.legs.steps.startLocation"); |
| 75 | + connection.setDoOutput(true); |
| 76 | + |
| 77 | + // Structure the JSON request body manually using standard JSONObjects |
| 78 | + JSONObject requestBody = new JSONObject(); |
| 79 | + |
| 80 | + JSONObject originLatLng = new JSONObject() |
| 81 | + .put("latitude", origin.latitude) |
| 82 | + .put("longitude", origin.longitude); |
| 83 | + requestBody.put("origin", new JSONObject() |
| 84 | + .put("location", new JSONObject().put("latLng", originLatLng))); |
| 85 | + |
| 86 | + JSONObject destLatLng = new JSONObject() |
| 87 | + .put("latitude", destination.latitude) |
| 88 | + .put("longitude", destination.longitude); |
| 89 | + requestBody.put("destination", new JSONObject() |
| 90 | + .put("location", new JSONObject().put("latLng", destLatLng))); |
| 91 | + |
| 92 | + requestBody.put("travelMode", "DRIVE"); |
| 93 | + |
| 94 | + // Stream payload to connection output |
| 95 | + try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream())) { |
| 96 | + writer.write(requestBody.toString()); |
| 97 | + writer.flush(); |
| 98 | + } |
| 99 | + |
| 100 | + int responseCode = connection.getResponseCode(); |
| 101 | + if (responseCode == HttpURLConnection.HTTP_OK) { |
| 102 | + StringBuilder response = new StringBuilder(); |
| 103 | + try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { |
| 104 | + String line; |
| 105 | + while ((line = reader.readLine()) != null) { |
| 106 | + response.append(line); |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + JSONObject jsonResponse = new JSONObject(response.toString()); |
| 111 | + JSONArray routes = jsonResponse.getJSONArray("routes"); |
| 112 | + if (routes.length() > 0) { |
| 113 | + JSONObject route = routes.getJSONObject(0); |
| 114 | + JSONObject polyline = route.getJSONObject("polyline"); |
| 115 | + String encodedPolyline = polyline.getString("encodedPolyline"); |
| 116 | + |
| 117 | + List<LatLng> navPoints = new ArrayList<>(); |
| 118 | + JSONArray legs = route.optJSONArray("legs"); |
| 119 | + if (legs != null && legs.length() > 0) { |
| 120 | + JSONObject leg = legs.getJSONObject(0); |
| 121 | + JSONArray steps = leg.optJSONArray("steps"); |
| 122 | + if (steps != null) { |
| 123 | + for (int i = 0; i < steps.length(); i++) { |
| 124 | + JSONObject step = steps.getJSONObject(i); |
| 125 | + JSONObject startLocation = step.optJSONObject("startLocation"); |
| 126 | + if (startLocation != null) { |
| 127 | + JSONObject latLngObj = startLocation.getJSONObject("latLng"); |
| 128 | + navPoints.add(new LatLng( |
| 129 | + latLngObj.getDouble("latitude"), |
| 130 | + latLngObj.getDouble("longitude") |
| 131 | + )); |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + } |
| 136 | + navPoints.add(destination); // Cap route off with final destination |
| 137 | + return new RouteData(encodedPolyline, navPoints); |
| 138 | + } else { |
| 139 | + throw new Exception("No route details returned from the server."); |
| 140 | + } |
| 141 | + } else { |
| 142 | + StringBuilder errorResponse = new StringBuilder(); |
| 143 | + try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) { |
| 144 | + String line; |
| 145 | + while ((line = reader.readLine()) != null) { |
| 146 | + errorResponse.append(line); |
| 147 | + } |
| 148 | + } |
| 149 | + throw new Exception("HTTP error " + responseCode + ": " + errorResponse); |
| 150 | + } |
| 151 | + }; |
| 152 | + } |
| 153 | +} |
0 commit comments