如何在Java中获得谷歌距离矩阵Api的距离

时间:2018-01-27 12:28:07

标签: java json google-distancematrix-api

我试图使用谷歌距离矩阵api找到两个地方之间的距离和时间 一切都很好,直到我得到这个数据

{
   "destination_addresses" : [
      "Some Address"
   ],
   "origin_addresses" : [ "Some other address" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "13.1 km",
                  "value" : 13133
               },
               "duration" : {
                  "text" : "33 mins",
                  "value" : 1961
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

我尝试使用Json库提取距离并尝试了很多答案,但是dint得到了预期的结果,任何帮助?

2 个答案:

答案 0 :(得分:0)

如果要解析json,可以使用Java中的json库,如JacksonGson Json simple。 第二种方式(我建议)您可以根据来自API的json请求和响应创建自己的Java请求和响应bean,并在http请求中使用它们,您可以从here找到完整示例

package com.apartmentnotification.client;

import com.apartmentnotification.model.DirectionResponse;
import java.io.IOException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;

public class ApartmentClient {

private static final String BASE_URI = "https://maps.googleapis.com/maps/api";
private static final String API_KEY = "AIzaSyCXnwOwrv_Kt7bkbO5vXtpPelu08yp-3iY";

/**
 * end point for read distanceMatrix
 */
private WebTarget distanceMatrix;

public ApartmentClient() {
    Client client = LazySingleton.getClient();
    distanceMatrix = client.target(BASE_URI + "/distancematrix");

}

public DirectionResponse getDirectionInfo(String origins, String destionations) throws IOException {
    return distanceMatrix.path("/json")
            .queryParam("units", "imperial")
            .queryParam("origins", origins)
            .queryParam("destinations", destionations)
            .queryParam("key", API_KEY)
            .request()
            .get()
            .readEntity(DirectionResponse.class);
}

public static void main(String[] args) throws IOException {
    ApartmentClient wc = new ApartmentClient();
    DirectionResponse direction = wc.getDirectionInfo("Vaidavas 6/3", "Domina Shopping");
    System.out.println("Duration in hours :"+direction.getRows().get(0).getElements().get(0).getDuration().getText());
    System.out.println("Distance  in metr : "+direction.getRows().get(0).getElements().get(0).getDistance().getValue());
}

}

希望它有所帮助。

答案 1 :(得分:0)

这是如何使用Google距离矩阵api计算两个地方之间的距离和时间的完整答案。 如果您不使用maven,则必须在类路径中设置这些jars

pom.xml

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.0</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/com.squareup.okio/okio -->
<dependency>
    <groupId>com.squareup.okio</groupId>
    <artifactId>okio</artifactId>
    <version>1.12.0</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

  <!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client -->
<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.23.0</version>
</dependency>

这是一个用于发送http请求并以json格式获取数据的类

 package google.distance.api;

import java.io.IOException;

import org.springframework.stereotype.Component;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Component
public class DistanceTime {



    private static final String API_KEY="YOUR KEY";
    OkHttpClient client = new OkHttpClient();


public String calculate(String source ,String destination) throws IOException {
String url="https://maps.googleapis.com/maps/api/distancematrix/json?origins="+source+"&destinations="+destination+"&key="+ API_KEY;
            Request request = new Request.Builder()
                .url(url)
                .build();

            Response response = client.newCall(request).execute();
            return response.body().string();
          }


}

当我使用Spring时,这是我的Controller方法来获取数据

private DistanceTime distance;

     @Autowired
    public void setDistance(DistanceTime distance) {
    this.distance = distance;
}


    public ModelAndView Api(@RequestParam("picking_up") String source,@RequestParam("dropping_off") String destination,@RequestParam("pick_up_date") String time) {
            try {
                  //method of DistanceTime Class
                String response=distance.calculate(source,destination);

            System.out.println(response);
            }

            catch(Exception e) {
                System.out.println("Exception Occurred");
            }

            return new ModelAndView("home");

        }  

现在,困难部分正在遍历JSON数据以获取距离和时间   在上面的方法中,我以可变的响应获取json数据,因此这是从中提取距离和时间的代码 响应就像

{
   "destination_addresses" : [
      "Private"
   ],
   "origin_addresses" : [ "Private" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1,052 km",
                  "value" : 1051911
               },
               "duration" : {
                  "text" : "17 hours 10 mins",
                  "value" : 61785
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}



 JSONParser parser = new JSONParser();
        try {

         Object obj = parser.parse(response);
         JSONObject jsonobj=(JSONObject)obj;

         JSONArray dist=(JSONArray)jsonobj.get("rows");
         JSONObject obj2 = (JSONObject)dist.get(0);
         JSONArray disting=(JSONArray)obj2.get("elements");
         JSONObject obj3 = (JSONObject)disting.get(0);
         JSONObject obj4=(JSONObject)obj3.get("distance");
         JSONObject obj5=(JSONObject)obj3.get("duration");
         System.out.println(obj4.get("text"));
         System.out.println(obj5.get("text"));

    }
catch(Exception e) {
    e.printStackTrace();
}