i have a console application, needs to find the distance and route between two places using the google maps api. that means i do not have a browser and hence no javascript. is it possible to do it using java using a HTTP request or something. i have tried geocoding and can find the latitude and longitude of a given address using HTTP requests. how to find distance and routes using java.
3 Answers
Google only provides this in javascript. However, there is a request to provide it in java also. So possibly, it will be there in the near future.
The fact that there is no out-of-the-box solution from google, doesn't mean that you can not create one for yourselve of course...
[EDIT] For example, you could read the sourcecode of your directions in html to find the distance and the route.
1 Comment
You can use official Java Client for Google Maps
<dependency>
<groupId>com.google.maps</groupId>
<artifactId>google-maps-services</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
Take a look at com.google.maps.DistanceMatrixApi and com.google.maps.DirectionsAPI
Code sample for Distance Matrix API (Documentation):
public static List<DistanceMatrixRow> distance() {
List<DistanceMatrixRow> results = new ArrayList<>();
try {
GeoApiContext ctx = new GeoApiContext.Builder().apiKey(API_KEY).build();
String[] origins = {"New Yourk, NY"};
String[] destinations = {"Jersey City, NJ"};
DistanceMatrix response = DistanceMatrixApi.getDistanceMatrix(ctx, origins, destinations)
.units(Unit.METRIC)
.mode(TravelMode.DRIVING)
.await();
results.addAll(Arrays.asList(response.rows));
} catch (ApiException e) {
logger.error("ApiException: ", e);
} catch (InterruptedException e) {
logger.error("InterruptedException: ", e);
} catch (IOException e) {
logger.error("IOException: ", e);
}
return results;
}
Code sample for Directions API (Documentation)
public static List<DirectionsRoute> routes() {
List<DirectionsRoute> results = new ArrayList<>();
try {
GeoApiContext ctx = new GeoApiContext.Builder().apiKey(API_KEY).build();
String origin = "New Yourk, NY";
String destination = "Jersey City, NJ";
DirectionsResult response = DirectionsApi.getDirections(ctx, origin, destination)
.units(Unit.METRIC)
.mode(TravelMode.TRANSIT)
.transitMode(TransitMode.BUS)
.await();
Arrays.stream(response.geocodedWaypoints).forEach(System.out::println);
results.addAll(Arrays.asList(response.routes));
} catch (ApiException e) {
logger.error("ApiException: ", e);
} catch (InterruptedException e) {
logger.error("InterruptedException: ", e);
} catch (IOException e) {
logger.error("IOException: ", e);
}
return results;
}
I invested my own time to investigate how to use Google Maps SDK. At the time I was looking at this there was no any docs on how to use that Java Client. If you found my answer helpful, please consider leaving a vote.