从Google获取json响应将API放置在android中



我的简单android应用程序使用谷歌位置api来获取一个地方的纬度和经度。我从谷歌api得到json响应,如下所示

 {
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Chennai",
               "short_name" : "Chennai",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Chennai",
               "short_name" : "Chennai",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Tamil Nadu",
               "short_name" : "TN",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Chennai, Tamil Nadu, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 13.23408510,
                  "lng" : 80.33229129999999
               },
               "southwest" : {
                  "lat" : 12.94592670,
                  "lng" : 80.14878270
               }
            },
            "location" : {
               "lat" : 13.0604220,
               "lng" : 80.2495830
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 13.14736150,
                  "lng" : 80.37764240
               },
               "southwest" : {
                  "lat" : 12.97345190,
                  "lng" : 80.12152360
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

现在我想在json响应中得到这一部分,

"location" : {
           "lat" : 13.0604220,
           "lng" : 80.2495830
        }

通过这种方法,我只得到整个"几何"部分作为字符串

JSONObject e = address.getJSONObject(0);
e.getString("geometry")

如何使用唯一的位置值。感谢您的帮助。我不确定出了什么问题。

JSONObject e = address.getJSONObject(0);
JSONObject jsonLocation = e.getJSONObject("geometry").getJSONObject("location");

并使用

String lat = jsonLocation.getString("lat");
String lng = jsonLocation.getString("lng");

获取纬度和经度。

您还可以获得如下位置值:

对于经度:

Double lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");

对于纬度:

Double lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");

试试这个。它对我有效。

JSONObject result = jsonObject.getJSONObject("result");
Double lat = result.getJSONObject("geometry").getJSONObject("location").getDouble("lat");
Double lng = result.getJSONObject("geometry").getJSONObject("location").getDouble("lng");

相关内容

  • 没有找到相关文章

最新更新