本篇文章主要内容来自于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;
}