Reputation: 214
The Problem I seem to be having is accessing the "deeper level" lat lng values from within the json file.
The Json file is being accessed live from google with this type of link: https://maps.googleapis.com/maps/api/place/nearbysearch/json?
Here is what a single object/array item looks like in json, including the "top Level" "results".
"results" : [
{
"geometry" : {
"location" : {
"lat" : 55.4628609,
"lng" : -4.6299348
},
"viewport" : {
"northeast" : {
"lat" : 55.46420472989273,
"lng" : -4.628674020107278
},
"southwest" : {
"lat" : 55.46150507010728,
"lng" : -4.631373679892723
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
"id" : "0655ceeeddd83f1a901bcef361b22cbfa951ae73",
"name" : "GAME",
"opening_hours" : {
"open_now" : false
},
"place_id" : "ChIJM8hBpZ3WiUgRuWc3KhfMJys",
"plus_code" : {
"compound_code" : "F97C+42 Ayr, UK",
"global_code" : "9C7QF97C+42"
},
"rating" : 4.2,
"reference" : "ChIJM8hBpZ3WiUgRuWc3KhfMJys",
"scope" : "GOOGLE",
"types" : [ "electronics_store", "store", "point_of_interest", "establishment" ],
"vicinity" : "120 High St, Ayr"
},
Here is the Method im using to access the json file data after it has been parsed to string.
void createMarkersFromJson(String json) throws JSONException {
JSONObject object = new JSONObject(json);
JSONArray jsonArray = object.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("name"))
.position(new LatLng(
jsonObj.getJSONArray("geometry").getDouble(0),
jsonObj.getJSONArray("geometry").getDouble(1)
))
);
}
}
Upvotes: 2
Views: 122
Reputation: 753
Geometry is not an array. JSON that begins with CURLY BRACE {} is an object while BRACKET [ ] indicates an array. Try this one.
JSONArray jsonArray= object.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject locationObj = jsonObj .getJSONObject("geometry")
.getJSONObject("location");
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("name"))
.position(new LatLng(
locationObj.getDouble("lat"),
locationObj.getDouble("lng")
))
);
}
Hope this helps you clarify difference between JSON array and object, and how to access them. Cheers
Upvotes: 1