解析Google Directions并写入文件

时间:2015-08-21 21:35:09

标签: java json org.json

我尝试解析google maps API路线结果,并在文件上写下每个坐标{lat,lng}点。

碰巧我想以下列格式编写文件:** lat; lng **(坐标前面有空格),但是json以这种格式回答每一步:

"end_location" : {
                    "lat" : 43.6520686,
                    "lng" : -79.38291280000001
                 },

我无法摆脱“lat”和“lng” 这是我的代码。

 // build a URL
String s = "https://maps.googleapis.com/maps/api/directions/json?origin=";      
s += URLEncoder.encode(origin, "UTF-8");
s += "&destination=";
s += URLEncoder.encode(destination, "UTF-8");
s += "&key=AIzaSyARNFl6ns__p2OEy3uCrZMGem8KW8pXwAI";
URL url = new URL(s);

// read from the URL
Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
    str += scan.nextLine();
scan.close();

final JSONObject json = new JSONObject(str);
final JSONObject jsonRoute = json.getJSONArray("routes").getJSONObject(0);
//Get the leg, only one leg as we don't support waypoints
final JSONObject leg = jsonRoute.getJSONArray("legs").getJSONObject(0);
//Get the steps for this leg
final JSONArray steps = leg.getJSONArray("steps");
//Number of steps for use in for loop
final int numSteps = steps.length();
//Set the name of this route using the start & end addresses

FileWriter coordinatesWrite = 
        new FileWriter("./resources/locations.txt", false);     

for(int i = 0; i< numSteps; ++i){
    final JSONObject step = steps.getJSONObject(i);
    final JSONObject startLocation = step.getJSONObject("start_location");
    final JSONObject endLocation = step.getJSONObject("end_location");

coordinatesWrite.write(" ");    
coordinatesWrite.write(startLocation.toString());
coordinatesWrite.write(";" + " ");
coordinatesWrite.write(endLocation.toString());
coordinatesWrite.write("\n");  
}
coordinatesWrite.close(); }

1 个答案:

答案 0 :(得分:0)

在JSONObject上尝试getDouble(String)方法:

final JSONObject startLocation = step.getJSONObject("start_location");
final double startLat = startLocation.getDouble("lat");
final double startLng = startLocation.getDouble("lng");

final JSONObject endLocation = step.getJSONObject("end_location");
final double endLat = endLocation.getDouble("lat");
final double endLng = endLocation.getDouble("lng");