【发布时间】:2016-07-27 15:09:09
【问题描述】:
是否有任何智能方法(算法、API 等)可以让我估算两个地理位置之间的到达时间,而这些地理位置只不过是两个人试图在地图上相互联系吗?
【问题讨论】:
标签: java android google-maps
是否有任何智能方法(算法、API 等)可以让我估算两个地理位置之间的到达时间,而这些地理位置只不过是两个人试图在地图上相互联系吗?
【问题讨论】:
标签: java android google-maps
与described by RJ Aylward 一样,您可以使用 Google 的路线 API 来估算从一个地方到另一个地方所需的时间,同时考虑路线和交通情况。但是您不必使用 Web API 并构建自己的包装器,而是使用 Google 自己提供的 Java implementation,它可以通过 Maven/gradle 存储库获得。
Add the google-maps-services to your app's build.gradle:
dependencies {
compile 'com.google.maps:google-maps-services:0.2.5'
}
执行请求并提取持续时间:
// - Put your api key (https://developers.google.com/maps/documentation/directions/get-api-key) here:
private static final String API_KEY = "AZ.."
/**
Use Google's directions api to calculate the estimated time needed to
drive from origin to destination by car.
@param origin The address/coordinates of the origin (see {@link DirectionsApiRequest#origin(String)} for more information on how to format the input)
@param destination The address/coordinates of the destination (see {@link DirectionsApiRequest#destination(String)} for more information on how to format the input)
@return The estimated time needed to travel human-friendly formatted
*/
public String getDurationForRoute(String origin, String destination)
// - We need a context to access the API
GeoApiContext geoApiContext = new GeoApiContext.Builder()
.apiKey(apiKey)
.build();
// - Perform the actual request
DirectionsResult directionsResult = DirectionsApi.newRequest(geoApiContext)
.mode(TravelMode.DRIVING)
.origin(origin)
.destination(destination)
.await();
// - Parse the result
DirectionsRoute route = directionsResult.routes[0];
DirectionsLeg leg = route.legs[0];
Duration duration = leg.duration;
return duration.humanReadable;
}
为简单起见,此代码不处理异常、错误情况(例如,找不到路由 -> routes.length == 0),也不会处理多个route 或leg。起点和终点也可以直接设置为LatLng 实例(参见DirectionsApiRequest#origin(LatLng) 和DirectionsApiRequest#destination(LatLng)。
延伸阅读:android.jlelse.eu - Google Maps Directions API
这是我在Android - How to get estimated drive time from one place to another?已经给出的答案
【讨论】:
您的问题没有直接的解决方案。
但是 google 提供了google direction api。这个api给出 您能够计算从一个位置到另一个位置的距离 并且还为您提供预计时间,但有这些限制-
所以要实现你想要的,你必须自己做很多事情。主计算。
您需要的 api 是 navigation api 。但不幸的是,这不是谷歌提供的供公众使用的。
希望这个答案对你有所帮助。
【讨论】:
Google Maps Directions Api 为您提供了一种获取两点之间行程的预计行程时间的方法,因此如果您知道两个用户的位置,您就可以利用它。
例如,如果您发送https://maps.googleapis.com/maps/api/directions/json?origin=NewYork&destination=LosAngeles&mode=walking 部分响应将包括
duration: {
text: "37 days 23 hours",
value: 3278737
}
实施细节取决于您的应用程序的工作方式,但 api 当然可以作为起点。
【讨论】: