2016-11-12 2 views
2

Ich habe die Abhängigkeit Google Maps API Java Client in meinem Java-Projekt hinzugefügt. Ich habe eine Reihe von Ursprung Entfernungen, Zielabstand und auch teh GeoApiContext als solche:So verwenden Sie Google Maps Entfernungsmatrix JAVA API, um den kürzesten Abstand zwischen Quelle und mehreren Zielen zu erhalten

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

Ich möchte das erhalten Entfernungen zwischen diesen Punkten (Flugzeug?). Ich weiß, dass wir eine einfache HTTP-Anfrage senden können wie
https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=40.6655101,-73.89188969999998&destinations=40.690515%73.6334271&key=YOUR_API_KEY
Aber ich möchte die JAVA Google Maps API verwenden. Ich habe versucht, DistanceMatrixApiRequest s = DistanceMatrixApi.getDistanceMatrix(context, originAddress, destinationAddress); tun, aber es gibt keine getArrivalTimes oder getDistanceMatrix oder auf jeden Fall, um eine Anfrage zu senden. Ich bin sehr verwirrt. PLZ Hilfe. Dank

+0

Die Entfernungsmatrix gibt keine geraden Linien ("in der Luftlinie", Großkreis) zurück, für diejenigen, die die Haversine-Formel verwenden. – geocodezip

+0

Ja Danke, ich habe das vor einiger Zeit erkannt und programmiert. Wie ich allerdings komme, sagen Fahrentfernungen von diesen Orten. Die API ist für mich verwirrend – tsaebeht

+0

[Bearbeiten] Ihre Frage bitte klar. – geocodezip

Antwort

0

Der Code Snapshot ist die folgende:

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

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

Die DistanceMatrix Antwortobjekt ist wie folgt aus:

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

Gut, das ist eine vollständige Antwort wie man Entfernung und Zeit mit Google Entfernung Matrix API zwischen zwei Orten zu berechnen. Wenn Sie mit Maven nicht, dann müssen Sie diese Gläser in Ihrem Classpath setzen

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> 

Dies ist eine Klasse HTTP-Anfrage zu senden und die Daten im JSON-Format

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


} 
bekommen

Als ich Frühling verwende, so ist hier mein Controller-Methode, die Daten zu bekommen

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

     } 

Nun wurde der Tough-Part über JSON-Daten iteriert, um die Entfernung und die Zeit zu erhalten. In der obigen Methode bekam ich Json-Daten in variabler Antwort, also hier ist der Code zum Extrahieren von Entfernung und Zeit Die Antwort war etwas wie

{ 
    "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(); 
} 
Verwandte Themen