如何在Android应用程序中找到2个地理点之间的距离(通过道路),而不使用谷歌地图方向api?
我正在开发一个Android应用程序。我需要找到两个地理坐标之间的距离如何在Android应用程序中找到2个地理点之间的距离(通过道路),而不使用谷歌地图方向api?,android,google-maps,Android,Google Maps,我正在开发一个Android应用程序。我需要找到两个地理坐标之间的距离 我使用了Location.distanceBetween()和Location.distanceTo()函数。这些功能给出了直线距离,但实际距离与我们在公路上行驶时不同。您可以使用Bing地图路由服务计算行驶距离。由于您正在创建一个移动应用程序,Bing地图的免费使用条款是谷歌提供的两倍。看看这项服务 您还可以在Android应用程序中找到如何使用此服务的示例 public float getDistance(double
我使用了
Location.distanceBetween()
和Location.distanceTo()
函数。这些功能给出了直线距离,但实际距离与我们在公路上行驶时不同。您可以使用Bing地图路由服务计算行驶距离。由于您正在创建一个移动应用程序,Bing地图的免费使用条款是谷歌提供的两倍。看看这项服务
您还可以在Android应用程序中找到如何使用此服务的示例
public float getDistance(double lat1, double lon1, double lat2, double lon2) {
String result_in_kms = "";
String url = "http://maps.google.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
String tag[] = {"text"};
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream is = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(is);
if (doc != null) {
NodeList nl;
ArrayList args = new ArrayList();
for (String s : tag) {
nl = doc.getElementsByTagName(s);
if (nl.getLength() > 0) {
Node node = nl.item(nl.getLength() - 1);
args.add(node.getTextContent());
} else {
args.add(" - ");
}
}
result_in_kms =String.valueOf( args.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
Float f=Float.valueOf(result_in_kms);
return f*1000;
}
或者您可以使用以下功能
public final static double AVERAGE_RADIUS_OF_EARTH = 6371;
public float calculateDistance(double userLat, double userLng, double venueLat, double venueLng) {
double latDistance = Math.toRadians(userLat - venueLat);
double lngDistance = Math.toRadians(userLng - venueLng);
double a = (Math.sin(latDistance / 2) * Math.sin(latDistance / 2)) +
(Math.cos(Math.toRadians(userLat))) *
(Math.cos(Math.toRadians(venueLat))) *
(Math.sin(lngDistance / 2)) *
(Math.sin(lngDistance / 2));
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return (float) (Math.round(AVERAGE_RADIUS_OF_EARTH * c));
}
为什么不使用google map direction api?很好,但是在
getDistance()
中,您必须搜索标记value
,而不是text
——否则args.get(0)
返回距离+单位(例如42公里)和String.valueOf()
会引发异常。更改字符串标记[]={“text”}代码>到字符串标记[]={“值”}代码>仅获取数字距离。