1
votes

I would like to ask how to achieve to get the coordinate in geocoding api which is like thisgeocoding api perimeter as of the moment I could be able to get the jsonresult of the geocoding api which has geometry" : { "bounds" : { "northeast" : { "lat" : 37.842911, "lng" : -85.682537 }, "southwest" : { "lat" : 37.559684, "lng" : -86.07509399999999 } }, "location" : { "lat" : 37.7030051, "lng" : -85.8647201 }, "location_type" : "APPROXIMATE", "viewport" : { "northeast" : { "lat" : 37.842911, "lng" : -85.682537 }, "southwest" : { "lat" : 37.559684, "lng" : -86.07509399999999 } } },

What might be the best part to use to achieve this perimeter like in the map?

1

1 Answers

4
votes

You can use the SphericalUtil.computeLength method from the Google Maps Android API Utility Library. This method receives a List<LatLng> as a parameter, and computes the length of the path, so your list will need to include a closed path.

You can decode your JSON and compute the perimeter like this:

try {
    String jsonString = "{ \"bounds\" : { \"northeast\" : { \"lat\" : 37.842911, \"lng\" : -85.682537 }, \"southwest\" : { \"lat\" : 37.559684, \"lng\" : -86.07509399999999 } }, \"location\" : { \"lat\" : 37.7030051, \"lng\" : -85.8647201 }, \"location_type\" : \"APPROXIMATE\", \"viewport\" : { \"northeast\" : { \"lat\" : 37.842911, \"lng\" : -85.682537 }, \"southwest\" : { \"lat\" : 37.559684, \"lng\" : -86.07509399999999 } } }";
    JSONObject object = new JSONObject(jsonString);

    JSONObject boundsJSON = object.getJSONObject("bounds");
    LatLng northeast = getLatLng(boundsJSON.getJSONObject("northeast"));
    LatLng southwest = getLatLng(boundsJSON.getJSONObject("southwest"));
    LatLng northwest = new LatLng(northeast.latitude, southwest.longitude);
    LatLng southeast = new LatLng(southwest.latitude, northeast.longitude);

    List<LatLng> path = new ArrayList<>();
    path.add(northwest);
    path.add(northeast);
    path.add(southeast);
    path.add(southwest);
    path.add(northwest);
    double perimeter = SphericalUtil.computeLength(path);
} catch (JSONException e) {
    // TODO: Handle the exception
    String a = "";
}

This is the getLatLng method that decodes a coordinate (used in the code above):

private LatLng getLatLng(JSONObject coordinateJSON) throws JSONException {
    double lat = coordinateJSON.getDouble("lat");
    double lon = coordinateJSON.getDouble("lng");

    return new LatLng(lat, lon);
}