Reputation: 163
In the following code the "results", "geometry", "location", "lat" and "lng" are hardcoded.
The problem is, if Google changes some of those words my code won't work anymore. So my question is: is there a method in the Google maps API or the JSON library which solves my problem?
private Location getCoordinates(Location l, JSONObject json) {
try {
JSONArray jsonObject1 = (JSONArray) json.get("results");
JSONObject jsonObject2 = (JSONObject)jsonObject1.get(0);
JSONObject jsonObject3 = (JSONObject)jsonObject2.get("geometry");
JSONObject location = (JSONObject) jsonObject3.get("location");
l.setLat(Double.parseDouble(location.get("lat").toString()));
l.setLon(Double.parseDouble(location.get("lng").toString()));
return l;
} catch (Exception e) {
throw new IllegalArgumentException("Country or zip not found.");
}
}
Upvotes: 1
Views: 133
Reputation: 4841
You can use Google client lib. Then you might get the coordinates like this.
GeoApiContext context = new GeoApiContext().setApiKey("API_KEY");
GeocodingResult[] results = GeocodingApi.geocode(context,
"1600 Amphitheatre Parkway Mountain View, CA 94043").await();
for (GeocodingResult result : results) {
System.out.println("LAT: " + result.geometry.location.lat);
System.out.println("LNG: " + result.geometry.location.lng);
}
Upvotes: 1