我正在开发一个Android应用程序。我需要找到两个地理坐标之间的距离。
我使用了Location.distanceBetween()
和Location.distanceTo()
个函数。这些功能给出了直线距离,但是当我们通过公路旅行时,实际距离是不同的。
答案 0 :(得分:8)
使用google api
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));
}
答案 1 :(得分:0)