如何使用Google Maps Distance Matrix JAVA API获取源和多个目标之间的最近距离

时间:2016-11-12 09:04:41

标签: java google-maps google-distancematrix-api

我在我的Java项目中添加了Google Maps API Java Client的依赖项。我有一组原点距离,目的地距离以及GeoApiContext:

GeoApiContext context = new GeoApiContext().setApiKey(MY_API_KEY);
String[] destinationAddress = {"40.7127837,-74.0059413", "33.9533487,-117.3961564", "38.6270025,-90.19940419999999"};
String[] originAddress = {"12.8445,80.1523"};

我想得到(飞机?)这些点之间的距离。我知道我们可以发送一个像https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=40.6655101,-73.89188969999998&destinations=40.690515%73.6334271&key=YOUR_API_KEY 这样的简单HTTP请求
但我想使用JAVA Google Maps API。我尝试过DistanceMatrixApiRequest s = DistanceMatrixApi.getDistanceMatrix(context, originAddress, destinationAddress);,但没有getArrivalTimesgetDistanceMatrix或无论如何都要发送请求。我很迷茫。 Plz的帮助。感谢

3 个答案:

答案 0 :(得分:4)

试试这个:

private static final String API_KEY = "YOUR_API_KEY";
private static final GeoApiContext context = new GeoApiContext().setApiKey(API_KEY);


public DistanceMatrix estimateRouteTime(DateTime time, Boolean isForCalculateArrivalTime, DirectionsApi.RouteRestriction routeRestriction, LatLng departure, LatLng... arrivals) {
    try {
        DistanceMatrixApiRequest req = DistanceMatrixApi.newRequest(context);
        if (isForCalculateArrivalTime) {
            req.departureTime(time);
        } else {
            req.arrivalTime(time);
        }
        if (routeRestriction == null) {
            routeRestriction = DirectionsApi.RouteRestriction.TOLLS;
        }
        DistanceMatrix trix = req.origins(departure)
                .destinations(arrivals)
                .mode(TravelMode.DRIVING)
                .avoid(routeRestriction)
                .language("fr-FR")
                .await();
        return trix;

    } catch (ApiException e) {
        System.out.println(e.getMessage());
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return null;
}

DistanceMatrix响应对象如下:

{
   "destination_addresses" : [ "San Francisco, Californie, États-Unis" ],
   "origin_addresses" : [ "Seattle, Washington, États-Unis" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1 300 km",
                  "value" : 1299878
               },
               "duration" : {
                  "text" : "12 heures 32 minutes",
                  "value" : 45146
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

答案 1 :(得分:1)

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

的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");

        }  

现在Tough Part正在迭代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();
}

答案 2 :(得分:0)

代码快照如下:

GeoApiContext context = new GeoApiContext().setApiKey(MY_API_KEY).setQueryRateLimit(QPS);
    try {
        DistanceMatrixApiRequest req = DistanceMatrixApi.newRequest(context); 
        DistanceMatrix trix = req.origins("Vancouver BC","Seattle")
                .destinations("San Francisco","Victoria BC")
                .mode(TravelMode.DRIVING)
                .avoid(RouteRestriction.HIGHWAYS)
                .language("fr-FR")
                .await();
        //Do something with result here
        // ....
    } catch(ApiException e){
        output += this.printError(e);
    } catch(Exception e){
        System.out.println(e.getMessage());
    }