Reputation: 284
EDIT: I have another program, which uses direction service. It works. When I use that code in this geocode project, it throws the same error. (Eclipse, Java EE, Tomcat7)
for reference here's the request
http://maps.googleapis.com/maps/api/geocode/json?address=vancouver,bc&sensor=true
Here's there code
JSONObject obj = new JSONObject(s);
JSONObject res = obj.getJSONArray("results").getJSONObject(0);
String "s" is the return json. This works:
System.out.println(obj.getJSONArray("results");
Though as soon as I try getJSONObject(0) I get the error. I was working with the directions service prior to this and it sends a very similar result.. which was working for me. Any advice is much appreciated! This has eaten a couple hours of my night now so I thought I'd seek some help.
Upvotes: 0
Views: 2473
Reputation: 1
As you can see here:
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
**"lat"** : 37.4223329,
**"lng"** : -122.0844192
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4236818802915,
"lng" : -122.0830702197085
},
"southwest" : {
"lat" : 37.4209839197085,
"lng" : -122.0857681802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
lat(Latitude)
and lng(Longitude)
are of type Double
, hence the correct code (if you need latitude and longitude as String
s) is:
String latitude = Double.toString(jsonTree.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
String longitude = Double.toString(jsonTree.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
Upvotes: 0
Reputation: 21
String lat = obj.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getString("lat");
Upvotes: 2