我知道有很多关于这个问题的话题,但我的问题更具体。 我调用Google Directions http API来获取两个位置之间的路由。响应JSON具有如何从A点移动到B的所有信息。但是如何在我移动时如何自己计算距离,例如我的实际位置和步骤的下一个结束位置?我需要“路线”而不是“空中线路”。
我所做的是使用LocationManager获取我的实际位置的lat,lng。使用this和lat,lng的结束位置,我调用Location.distanceBetween方法。但它给出了一个不准确的距离..不精确意味着方法之间的距离的结果不同于方向API之外的距离。对于漫长的方式而言。
一种解决方案是多次调用Directions API ......但是必须有更好的工作来获得沿着道路的实际距离。有没有工具可以得到我想要的东西?
编辑使其更容易理解
答案 0 :(得分:1)
拨打Directions API:
public Document getDocument(LatLng start, LatLng end, String mode) {
String url = "http://maps.googleapis.com/maps/api/directions/xml?"
+ "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode=driving";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
之后,你可以运行你在文档中收到的所有json对象,并检查每对点之间的距离:
public int getDistanceValue (Document doc) {
NodeList nl1 = doc.getElementsByTagName("distance");
Node node1 = nl1.item(0);
NodeList nl2 = node1.getChildNodes();
Node node2 = nl2.item(getNodeIndex(nl2, "value"));
Log.i("DistanceValue", node2.getTextContent());
return Integer.parseInt(node2.getTextContent());
}
以下是获得所有观点的方法:
public ArrayList<LatLng> getDirection (Document doc) {
NodeList nl1, nl2, nl3;
ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
nl1 = doc.getElementsByTagName("step");
if (nl1.getLength() > 0) {
for (int i = 0; i < nl1.getLength(); i++) {
Node node1 = nl1.item(i);
nl2 = node1.getChildNodes();
Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
nl3 = locationNode.getChildNodes();
Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
double lat = Double.parseDouble(latNode.getTextContent());
Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
double lng = Double.parseDouble(lngNode.getTextContent());
listGeopoints.add(new LatLng(lat, lng));
locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
nl3 = locationNode.getChildNodes();
latNode = nl3.item(getNodeIndex(nl3, "points"));
ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
for(int j = 0 ; j < arr.size() ; j++) {
listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
}
locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
nl3 = locationNode.getChildNodes();
latNode = nl3.item(getNodeIndex(nl3, "lat"));
lat = Double.parseDouble(latNode.getTextContent());
lngNode = nl3.item(getNodeIndex(nl3, "lng"));
lng = Double.parseDouble(lngNode.getTextContent());
listGeopoints.add(new LatLng(lat, lng));
}
}
return listGeopoints;
}
实际上我使用此代码在地图上绘制Polyline
方向,但距离函数也应该有效。