Android 调用Google Map api v3路由两点间距离、时间以及解析方式

本文介绍了如何使用Google Maps API v3在Android中获取并解析两点间的路径、距离和时间信息。旧的方式是通过KML格式,而新的API返回JSON格式的数据,需要进行JSON解析。示例代码展示了如何发送请求、接收响应以及解析JSON来获取路线、距离和时间详情。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本篇文章主要内容来自于http://www.it1352.com/78696.html,我看完之后稍微做了整理

Google Map api v3 https://developers.google.com/maps/?hl=zh-cn

在2013年3月份之前,android通过google map获取路径详情方式为:

http://maps.google.com/maps?f=d&hl=en&saddr=31.242882,121.447273&daddr=31.243999,121.457989&ie=UTF8&0&om=0&output=kml

3月份之后google map api升级到v3,获取方式和解析方式也大有不同,升级后的获取方式为:

http://maps.googleapis.com/maps/api/directions/json?origin=31.242882,121.447273&destination=31.243999,121.457989&sensor=false&mode=walking

由于是以json方式返回,需要做如下解析:

private static Road getDistanceInfo(String url) {
//获取json详情,解析json
StringBuilder stringBuilder = new StringBuilder();
Road road = null;
try {
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) {
Logger.error("POPLocationModelgetDistanceInfo", e.toString());
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
road = new Road();
jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject roadInfo = legs.getJSONObject(0);
JSONObject distance = roadInfo.getJSONObject("distance");
JSONObject duration = roadInfo.getJSONObject("duration");
JSONArray steps = roadInfo.getJSONArray("steps");
road.mRoute = new double[steps.length()][2];//获取绘制路线所需要的坐标点
for (int i = 0; i < steps.length(); i++) {
JSONObject stepsInfo = steps.getJSONObject(i);
JSONObject end_location = stepsInfo.getJSONObject("end_location");
JSONObject start_location = stepsInfo.getJSONObject("start_location");
// Logger.log(5,"start_location",start_location.toString());
for (int j = 0; j < 2; j++){
String lat = start_location.getString("lat").trim();
String lng = start_location.getString("lng").trim();
}
}
String durationStr = duration.getString("text").trim();
String distanceStr = distance.getString("text").trim();
//.replaceAll("[^\\.0123456789]", "");
if(null != durationStr && null != distanceStr){
road.setDistance(distanceStr);
road.setDuration(durationStr);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Logger.error("getDistanceInfo",TPCConfiguration.getStackTrace(e));
e.printStackTrace();
}
return road;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值