Reputation: 33
I getting confused with how to get duration, time and distance traveled using google distancematrix.api I can't understand whats not working with my code, all that I'm getting are null values. why ?? Below is my javacode
DistanceMatrix results1 = DistanceMatrixApi.getDistanceMatrix(context,
new String[] {"rose hill"}, new String[] {"port louis"}).units(Unit.METRIC).await();
System.out.println(results1.rows[0].elements[0].duration);
System.out.println(results1.rows[0].elements[0].distance);
System.out.println(results1.rows[0].elements[0].distance);
context as requested
GeoApiContext context = new GeoApiContext.Builder()
.apiKey("AIzaSyC..")
.build();
Upvotes: 0
Views: 498
Reputation: 1327
It worked for me just by creating (and enabling) an API key on the google maps
Here is my code
public class GoogleDistance {
public static void main(String[] args) throws InterruptedException, ApiException, IOException {
new GoogleDistance().go();
}
void go() throws InterruptedException, ApiException, IOException {
String API_KEY = "AIzy....";
GeoApiContext.Builder builder = new GeoApiContext.Builder();
builder.apiKey(API_KEY);
GeoApiContext geoApiContext = builder.build();
DistanceMatrix results1 = DistanceMatrixApi.getDistanceMatrix(geoApiContext,
new String[]{"rose hill"}, new String[]{"port louis"}).units(Unit.METRIC).await();
System.out.println(Arrays.toString(results1.destinationAddresses));
}
}
I believe the issue may be with your prints: I don't think you should be doing rows[0].elements[0]
just use Arrays.toString().
When I run my code it outputs [Port Louis, Mauritius]
EDIT
I think I now see what you were trying to do. Please take a look at the following
public class GoogleDistance {
public static void main(String[] args) throws InterruptedException, ApiException, IOException {
new GoogleDistance().go();
}
void go() throws InterruptedException, ApiException, IOException {
String API_KEY = "AIzy...";
GeoApiContext.Builder builder = new GeoApiContext.Builder();
builder.apiKey(API_KEY);
GeoApiContext geoApiContext = builder.build();
DistanceMatrix results1 = DistanceMatrixApi.getDistanceMatrix(geoApiContext,
new String[]{"los angeles"}, new String[]{"san francisco"}).units(Unit.METRIC).await();
DistanceMatrixRow[] rows = results1.rows;
for (DistanceMatrixRow row : rows) {
DistanceMatrixElement[] elements = row.elements;
for (DistanceMatrixElement element : elements) {
Distance distance = element.distance;
if(distance == null){
System.out.println("distance is null");
continue;
}
String dist = distance.humanReadable;
String dur = element.duration.humanReadable;
System.out.println(dist);
System.out.println(dur);
}
}
}
}
I believe you're getting null because google cant map between the locations you're providing.
Upvotes: 1