-1

我试图解析谷歌地图 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(); }
4

1 回答 1

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");
于 2015-08-21T21:42:41.200 回答