Search code examples
javajsonorg.json

Parse Google Directions and write to a file


I trying to parse a google maps API directions result and write each coordinate {lat, lng} point on a file.

It happens that I would like to write the file in the format: ** lat; lng** (with space before the coordinates), but the json answers for each step in the this format:

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

I cannot get rid of "lat" and "lng".
Here is my code.

 // 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(); }

Solution

  • Try getDouble(String) method on JSONObject:

    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");