问题描述
我正在尝试获取特定地址的经度和纬度。
这是使用我正在使用的地址作为地址的GeoCoded响应的结果。
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600","short_name" : "1600","types" : [ "street_number" ]
},{
"long_name" : "Amphitheatre Pkwy","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",{
"long_name" : "California","short_name" : "CA","types" : [ "administrative_area_level_1",{
"long_name" : "United States","short_name" : "US","types" : [ "country",{
"long_name" : "94043","short_name" : "94043","types" : [ "postal_code" ]
}
],"formatted_address" : "1600 Amphitheatre Parkway,Mountain View,CA 94043,USA","geometry" : {
"location" : {
"lat" : 37.4224764,"lng" : -122.0842499
},"location_type" : "ROOFTOP","viewport" : {
"northeast" : {
"lat" : 37.4238253802915,"lng" : -122.0829009197085
},"southwest" : {
"lat" : 37.4211274197085,"lng" : -122.0855988802915
}
}
},"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA","plus_code": {
"compound_code": "CWC8+W5 Mountain View,California,United States","global_code": "849VCWC8+W5"
},"types" : [ "street_address" ]
}
],"status" : "OK"
}
我需要特定的JSON字段,以便可以在Java代码中使用它
解决方法
我找到了解决方法。
github页面中的代码显示:
GeoApiContext context = new GeoApiContext.Builder().apiKey("AIza...").build();
GeocodingResult[] results = GeocodingApi.geocode(context,"1600 Amphitheatre Parkway Mountain View,CA 94043").await();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(results[0].addressComponents));
第四行仅访问JSON字符串的“ addressComponents”。为了获得纬度,我只需要使用相应的字段名称,并将上面代码的第四行替换为:
System.out.println(gson.toJson(results[0].geometry.location.lat));