gpt4 book ai didi

android - 从 Android 中的 Google Direction API 获取距离

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:30:39 24 4
gpt4 key购买 nike

http://maps.googleapis.com/maps/api/directions/json?origin=-20.291825,57.448668&destination=-20.179724,57.613463&sensor=false&mode=%22DRIVING%22

例如,此链接生成以下内容:

"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : -20.1765204,
"lng" : 57.6137001
},
"southwest" : {
"lat" : -20.2921672,
"lng" : 57.4472155
}
},
"copyrights" : "Map data ©2014 Google",
"legs" : [
{
"distance" : {
"text" : "24.6 km",
"value" : 24628
},

我只想提取距离并在android中显示

最佳答案

要获取与 Google map 的距离,您可以使用 Google Directions API 和 JSON 解析器来检索距离值。

示例方法

private double getDistanceInfo(double lat1, double lng1, String destinationAddress) {
StringBuilder stringBuilder = new StringBuilder();
Double dist = 0.0;
try {

destinationAddress = destinationAddress.replaceAll(" ","%20");
String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + latFrom + "," + lngFrom + "&destination=" + latTo + "," + lngTo + "&mode=driving&sensor=false";

HttpPost httppost = new HttpPost(url);

HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();


response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}

JSONObject jsonObject = new JSONObject();
try {

jsonObject = new JSONObject(stringBuilder.toString());

JSONArray array = jsonObject.getJSONArray("routes");

JSONObject routes = array.getJSONObject(0);

JSONArray legs = routes.getJSONArray("legs");

JSONObject steps = legs.getJSONObject(0);

JSONObject distance = steps.getJSONObject("distance");

Log.i("Distance", distance.toString());
dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") );

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return dist;
}

有关参数的详细信息以及有关可用的不同选项的更多详细信息,请参阅此内容。

https://developers.google.com/maps/documentation/directions/

关于android - 从 Android 中的 Google Direction API 获取距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20979853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com