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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40561264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:19:08  来源:igfitidea点击:

How to use Google Maps Distance Matrix JAVA API to obtain closest distance between source and multiple destinations

javagoogle-mapsgoogle-distancematrix-api

提问by tsaebeht

I have added the dependency of Google Maps API Java Clientin my Java project. I have a set of origin distances, destination distance and also teh GeoApiContext as such:

我在我的 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"};

I want to get the (Airplane?) Distances between these points. I know we can send a simple HTTP request like
https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=40.6655101,-73.89188969999998&destinations=40.690515%73.6334271&key=YOUR_API_KEY
But I want to use the JAVA Google Maps API. I have tried to do DistanceMatrixApiRequest s = DistanceMatrixApi.getDistanceMatrix(context, originAddress, destinationAddress);but there is no getArrivalTimesor getDistanceMatrixor anyway to send request. I am very confused. Plz help. Thanks

我想获得这些点之间的(飞机?)距离。我知道我们可以发送一个简单的 HTTP 请求,例如
https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=40.6655101,-73.89188969999998&destinations=40.690515%73.6334271&key=YOUR_API_KEY
But I want to use the JAVA Google Maps API。我试图做的DistanceMatrixApiRequest s = DistanceMatrixApi.getDistanceMatrix(context, originAddress, destinationAddress);,但没有getArrivalTimesgetDistanceMatrix或反正发送请求。我很迷茫。请帮忙。谢谢

回答by MK-rou

Try this :

试试这个 :

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;
}

The DistanceMatrix response object is like that :

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"
}

回答by Shubh

Well this is a complete answer of how to calculate distance and time with google distance matrix api between two places. If you are not using maven then you have to set these jars in your classpath

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

pom.xml

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>

This is a class to send http request and get the data in json format

这是一个发送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();
          }


}

As I am using Spring ,so here is my Controller method to get the data

因为我使用的是 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");

        }  

Now the Tough Part was iterating over JSON data to get the distance and time In the above method I was getting json data in variable response ,so here is the code to extract distance and time from it The response was something Like

现在艰难的部分是迭代 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();
}

回答by xomena

The code snapshot is the following:

代码快照如下:

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());
    }