Created
March 12, 2024 23:48
-
-
Save claeusdev/caac9f1701cc0524a2ccd41b2e27dbe1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.databind.ObjectMapper; | |
import org.springframework.http.HttpEntity; | |
import org.springframework.http.HttpMethod; | |
import org.springframework.http.ResponseEntity; | |
import org.springframework.web.client.RestTemplate; | |
import java.util.Objects; | |
public class RoutePlannerAdapter implements IDUServiceRoutePlanner { | |
private final String apiKey; | |
private final String baseUrl; | |
public RoutePlannerAdapter(String apiKey) { | |
this.apiKey = apiKey; | |
this.baseUrl = "https://maps.googleapis.com/maps/api/directions/json"; | |
} | |
@Override | |
public RouteDetails requestRouteAndEstimates(Address startLocation, Address targetLocation, String transportMeans) { | |
// Prepare the request URL | |
String url = baseUrl + "?origin=" + encodeAddress(startLocation) + | |
"&destination=" + encodeAddress(targetLocation) + | |
"&mode=" + transportMeans + | |
"&key=" + apiKey; | |
// Set up REST template | |
RestTemplate restTemplate = new RestTemplate(); | |
// Make the API call | |
ResponseEntity<RouteDetails> responseEntity = restTemplate.exchange( | |
url, | |
HttpMethod.GET, | |
null, | |
RouteDetails.class); | |
// Check if the response is successful | |
if (responseEntity.getStatusCode().is2xxSuccessful()) { | |
return Objects.requireNonNull(responseEntity.getBody()); | |
} else { | |
throw new RuntimeException("Failed to retrieve route details: " + responseEntity.getStatusCode()); | |
} | |
} | |
// Utility method to encode address for URL | |
private String encodeAddress(Address address) { | |
return address.getStreet() + ", " + address.getCity() + ", " + address.getPostalCode() + ", " + address.getCountry(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment