在复杂的Google地理编码JSON对象-Java-android中按键获取值
为了在android应用程序中获取当前位置,我使用了这个有用的工具,现在我想在Google Geocoding JSON对象中获取在复杂的Google地理编码JSON对象-Java-android中按键获取值,java,android,json,google-maps,Java,Android,Json,Google Maps,为了在android应用程序中获取当前位置,我使用了这个有用的工具,现在我想在Google Geocoding JSON对象中获取路线(街道地址)、街道号、邮政编码和国家(总是长名称)。目前,我使用do-while循环,然后拆分格式化的_地址,以获得所需的结果,但我认为最好通过其键访问该值 JSON如下所示: { "results": [ { "types": [ "street_address" ], "forma
路线
(街道地址)、街道号
、邮政编码
和国家
(总是长名称
)。目前,我使用do-while循环,然后拆分格式化的_地址
,以获得所需的结果,但我认为最好通过其键访问该值
JSON如下所示:
{
"results": [
{
"types": [
"street_address"
],
"formatted_address": "RotenturmstraÃe 2, 1010 Vienna, Austria",
"address_components": [
{
"types": [
"street_number"
],
"short_name": "2",
"long_name": "2"
},
{
"types": [
"route"
],
"short_name": "Rotenturmstr.",
"long_name": "RotenturmstraÃe"
},
{
"types": [
"sublocality_level_1",
"sublocality",
"political"
],
"short_name": "Innere Stadt",
"long_name": "Innere Stadt"
},
{
"types": [
"locality",
"political"
],
"short_name": "Vienna",
"long_name": "Vienna"
},
{
"types": [
"administrative_area_level_1",
"political"
],
"short_name": "Vienna",
"long_name": "Vienna"
},
{
"types": [
"country",
"political"
],
"short_name": "AT",
"long_name": "Austria"
},
{
"types": [
"postal_code"
],
"short_name": "1010",
"long_name": "1010"
}
],
"geometry": {
"viewport": {
"southwest": {
"lng": 16.3719497197085,
"lat": 48.20797491970851
},
"northeast": {
"lng": 16.3746476802915,
"lat": 48.2106728802915
}
},
"location": {
"lng": 16.3732987,
"lat": 48.2093239
},
"location_type": "ROOFTOP"
}
},
{
"types": [
"neighborhood",
"political"
],
"formatted_address": "Stephansdom, 1010 Vienna, Austria",
"address_components": [
{
"types": [
"neighborhood",
"political"
],
"short_name": "Stephansdom",
"long_name": "Stephansdom"
},
{
"types": [
"sublocality_level_1",
"sublocality",
"political"
],
"short_name": "Innere Stadt",
"long_name": "Innere Stadt"
},
{
"types": [
"locality",
"political"
],
"short_name": "Vienna",
"long_name": "Vienna"
},
{
"types": [
"administrative_area_level_1",
"political"
],
"short_name": "Vienna",
"long_name": "Vienna"
},
{
"types": [
"country",
"political"
],
"short_name": "AT",
"long_name": "Austria"
},
{
"types": [
"postal_code"
],
"short_name": "1010",
"long_name": "1010"
}
],
"geometry": {
"bounds": {
"southwest": {
"lng": 16.3663459,
"lat": 48.2016949
},
"northeast": {
"lng": 16.382804,
"lat": 48.21546559999999
}
},
"viewport": {
"southwest": {
"lng": 16.3663459,
"lat": 48.2016949
},
"northeast": {
"lng": 16.382804,
"lat": 48.21546559999999
}
},
"location": {
"lng": 16.3767451,
"lat": 48.2083206
},
"location_type": "APPROXIMATE"
}
},
{
"types": [
"postal_code"
],
"formatted_address": "1010 Vienna, Austria",
"address_components": [
{
"types": [
"postal_code"
],
"short_name": "1010",
"long_name": "1010"
},
{
"types": [
"locality",
"political"
],
"short_name": "Vienna",
"long_name": "Vienna"
},
{
"types": [
"administrative_area_level_1",
"political"
],
"short_name": "Vienna",
"long_name": "Vienna"
},
{
"types": [
"country",
"political"
],
"short_name": "AT",
"long_name": "Austria"
}
],
"geometry": {
"bounds": {
"southwest": {
"lng": 16.3552218,
"lat": 48.1992606
},
"northeast": {
"lng": 16.3853131,
"lat": 48.2185876
}
},
"viewport": {
"southwest": {
"lng": 16.3552218,
"lat": 48.1992606
},
"northeast": {
"lng": 16.3853131,
"lat": 48.2185876
}
},
"location": {
"lng": 16.3677601,
"lat": 48.2083556
},
"location_type": "APPROXIMATE"
}
},
{
"types": [
"sublocality_level_1",
"sublocality",
"political"
],
"formatted_address": "Innere Stadt, 1010 Vienna, Austria",
"address_components": [
{
"types": [
"sublocality_level_1",
"sublocality",
"political"
],
"short_name": "Innere Stadt",
"long_name": "Innere Stadt"
},
{
"types": [
"locality",
"political"
],
"short_name": "Vienna",
"long_name": "Vienna"
},
{
"types": [
"administrative_area_level_1",
"political"
],
"short_name": "Vienna",
"long_name": "Vienna"
},
{
"types": [
"country",
"political"
],
"short_name": "AT",
"long_name": "Austria"
},
{
"types": [
"postal_code"
],
"short_name": "1010",
"long_name": "1010"
}
],
"geometry": {
"bounds": {
"southwest": {
"lng": 16.3552218,
"lat": 48.1992606
},
"northeast": {
"lng": 16.3853131,
"lat": 48.2185876
}
},
"viewport": {
"southwest": {
"lng": 16.3552218,
"lat": 48.1992606
},
"northeast": {
"lng": 16.3853131,
"lat": 48.2185876
}
},
"location": {
"lng": 16.3697428,
"lat": 48.2088774
},
"location_type": "APPROXIMATE"
}
},
{
"types": [
"administrative_area_level_1",
"political"
],
"formatted_address": "Vienna, Austria",
"address_components": [
{
"types": [
"administrative_area_level_1",
"political"
],
"short_name": "Vienna",
"long_name": "Vienna"
},
{
"types": [
"country",
"political"
],
"short_name": "AT",
"long_name": "Austria"
}
],
"geometry": {
"bounds": {
"southwest": {
"lng": 16.1826199,
"lat": 48.1182699
},
"northeast": {
"lng": 16.5774999,
"lat": 48.3230999
}
},
"viewport": {
"southwest": {
"lng": 16.1826199,
"lat": 48.1182699
},
"northeast": {
"lng": 16.5774999,
"lat": 48.3230999
}
},
"location": {
"lng": 16.3738138,
"lat": 48.20823499999999
},
"location_type": "APPROXIMATE"
}
}
]
这是我的密码:
public static JSONObject getLocationInfo(double lat, double lng) {
HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
public static String getCurrentLocationViaJSON(double lat, double lng) {
JSONObject jsonObj = getLocationInfo(lat, lng);
Log.i("JSON string =>", jsonObj.toString());
String currentLocation = "testing";
String street_address = null;
String postal_code = null;
try {
String status = jsonObj.getString("status").toString();
Log.i("status", status);
if(status.equalsIgnoreCase("OK")){
JSONArray results = jsonObj.getJSONArray("results");
int i = 0;
Log.i("i", i+ "," + results.length() ); //TODO delete this
do{
JSONObject r = results.getJSONObject(i);
JSONArray typesArray = r.getJSONArray("types");
String types = typesArray.getString(0);
if(types.equalsIgnoreCase("street_address")){
street_address = r.getString("formatted_address").split(",")[0];
Log.i("street_address", street_address);
}else if(types.equalsIgnoreCase("postal_code")){
postal_code = r.getString("formatted_address");
Log.i("postal_code", postal_code);
}
if(street_address!=null && postal_code!=null){
currentLocation = street_address + "," + postal_code;
Log.i("Current Location =>", currentLocation); //Delete this
i = results.length();
}
i++;
}while(i<results.length());
Log.i("JSON Geo Locatoin =>", currentLocation);
return currentLocation;
}
} catch (JSONException e) {
Log.e("testing","Failed to load JSON");
e.printStackTrace();
}
return null;
}
公共静态JSONObject getLocationInfo(双lat,双lng){
HttpGet HttpGet=新的HttpGet(“http://maps.googleapis.com/maps/api/geocode/json?latlng=“+lat+”、“+lng+”&传感器=真”);
HttpClient=new DefaultHttpClient();
HttpResponse响应;
StringBuilder StringBuilder=新的StringBuilder();
试一试{
response=client.execute(httpGet);
HttpEntity=response.getEntity();
InputStream=entity.getContent();
int b;
而((b=stream.read())!=-1){
stringBuilder.append((char)b);
}
}捕获(客户端协议例外e){
}捕获(IOE异常){
}
JSONObject JSONObject=新的JSONObject();
试一试{
jsonObject=新的jsonObject(stringBuilder.toString());
}捕获(JSONException e){
e、 printStackTrace();
}
返回jsonObject;
}
公共静态字符串getCurrentLocationViaJSON(双lat,双lng){
JSONObject jsonObj=getLocationInfo(纬度,液化天然气);
i(“JSON字符串=>”,jsonObj.toString());
字符串currentLocation=“测试”;
String street_address=null;
字符串邮政编码=空;
试一试{
String status=jsonObj.getString(“status”).toString();
Log.i(“状态”,状态);
if(状态相等信号情况(“正常”)){
JSONArray results=jsonObj.getJSONArray(“结果”);
int i=0;
Log.i(“i”,i+,“+results.length());//要删除这个吗
做{
JSONObject r=results.getJSONObject(i);
JSONArray类型array=r.getJSONArray(“类型”);
字符串类型=typesArray.getString(0);
if(类型.相等信号(“街道地址”)){
street_address=r.getString(“格式化的_address”).split(“,”[0];
Log.i(“街道地址”,街道地址);
}else if(类型.相等信号(“邮政编码”)){
邮政编码=r.getString(“格式化地址”);
Log.i(“邮政编码”,邮政编码);
}
如果(街道地址!=null和邮政编码!=null){
currentLocation=街道地址+“,”+邮政编码;
Log.i(“当前位置=>”,currentLocation);//删除此
i=结果。长度();
}
i++;
}在这个代码示例中,它们使用JSONObject,所以您需要使用getJSONObject(i)
、getJSONArray()
和getString()
来解析数据
可能最好使用这样的函数将数据解析成更可读的变量。否则,如果您直接使用它们键,您将得到类似String street\u address=jsonObj.getJSONArray(“results”).getJSONObject(i).getString(“formatted\u address”)
的结果,这很好,但非常庞大
另外,有点不清楚“最好通过键值访问值”是什么意思。在循环中,您是通过键值访问值。coder.getString(“格式化的\u地址”)
使用键值格式化的\u地址
访问该键值对的数据
这里有一个可能的解决方案:
public JSONObject getCurrentLocationViaJSON(double lat, double lng) {
// Returns a JSONObject with route (street_address), street_number, postal_code and country
JSONObject jsonObj = getLocationInfo(lat, lng);
Log.i("JSON string =>", jsonObj.toString());
String currentLocation = "testing";
String route = null;
String street_number = null;
String postal_code = null;
String country = null;
try {
String status = jsonObj.getString("status").toString();
Log.i("status", status);
if(status.equalsIgnoreCase("OK")){
JSONArray results = jsonObj.getJSONArray("results");
int i = 0;
Log.i("i", i+ "," + results.length() ); //TODO delete this
do{
JSONObject r = results.getJSONObject(0);
JSONArray addressComponentsArray = r.getJSONArray("address_components");
JSONArray addressComponents = addressComponentsArray.getJSONObject(i);
JSONArray typesArray = addressComponents.getJSONArray(0);
String types = typesArray.getString(0);
if(types.equalsIgnoreCase("street_number")){
street_number = addressComponents.getString("short_name");
Log.i("street_number", street_number);
}else if(types.equalsIgnoreCase("postal_code")){
postal_code = addressComponents.getString("long_name");
Log.i("postal_code", postal_code);
}else if(types.equalsIgnoreCase("country")){
country = addressComponents.getString("long_name");
Log.i("country", country);
}else if(types.equalsIgnoreCase("route")){
route = addressComponents.getString("long_name");
Log.i("postal_code", postal_code);
}
i++;
}while(i<results.length());
Log.i("JSON Geo Locatoin =>", currentLocation);
return currentLocation;
}
} catch (JSONException e) {
Log.e("testing","Failed to load JSON");
e.printStackTrace();
}
JSONObject json = new JSONObject();
json.put("street_number", street_number);
json.put("postal_code", postal_code);
json.put("country ", country);
json.put("route", route);
return json;
}
在这个代码示例中,他们使用JSONObject,所以您需要使用getJSONObject(i)
,getJSONArray()
,和getString()
来解析数据
可能最好使用这样的函数将数据解析成更可读的变量。否则,如果您直接使用它们键,您将得到类似String street\u address=jsonObj.getJSONArray(“results”).getJSONObject(i).getString(“formatted\u address”)
的结果,这很好,但非常庞大
另外,有点不清楚“最好通过键值访问值”是什么意思。在循环中,您是通过键值访问值。coder.getString(“格式化的\u地址”)
使用键值格式化的\u地址
访问该键值对的数据
这里有一个可能的解决方案:
public JSONObject getCurrentLocationViaJSON(double lat, double lng) {
// Returns a JSONObject with route (street_address), street_number, postal_code and country
JSONObject jsonObj = getLocationInfo(lat, lng);
Log.i("JSON string =>", jsonObj.toString());
String currentLocation = "testing";
String route = null;
String street_number = null;
String postal_code = null;
String country = null;
try {
String status = jsonObj.getString("status").toString();
Log.i("status", status);
if(status.equalsIgnoreCase("OK")){
JSONArray results = jsonObj.getJSONArray("results");
int i = 0;
Log.i("i", i+ "," + results.length() ); //TODO delete this
do{
JSONObject r = results.getJSONObject(0);
JSONArray addressComponentsArray = r.getJSONArray("address_components");
JSONArray addressComponents = addressComponentsArray.getJSONObject(i);
JSONArray typesArray = addressComponents.getJSONArray(0);
String types = typesArray.getString(0);
if(types.equalsIgnoreCase("street_number")){
street_number = addressComponents.getString("short_name");
Log.i("street_number", street_number);
}else if(types.equalsIgnoreCase("postal_code")){
postal_code = addressComponents.getString("long_name");
Log.i("postal_code", postal_code);
}else if(types.equalsIgnoreCase("country")){
country = addressComponents.getString("long_name");
Log.i("country", country);
}else if(types.equalsIgnoreCase("route")){
route = addressComponents.getString("long_name");
Log.i("postal_code", postal_code);
}
i++;
}while(i<results.length());
Log.i("JSON Geo Locatoin =>", currentLocation);
return currentLocation;
}
} catch (JSONException e) {
Log.e("testing","Failed to load JSON");
e.printStackTrace();
}
JSONObject json = new JSONObject();
json.put("street_number", street_number);
json.put("postal_code", postal_code);
json.put("country ", country);
json.put("route", route);
return json;
}
此代码将始终为您提供地址。验证
public class GeocodeLoader extends AsyncTask<Void, Void, String> {
private WeakReference<TextView> textView;
private WeakReference<ProgressBar> progressBar;
private WeakReference<LatLng> latLng;
private static WeakReference<Context> context;
private String urlString;
public GeocodeLoader ( Context context, LatLng latLng, TextView textView, ProgressBar progressBar) {
GeocodeLoader.context = new WeakReference<>(context);
this.textView = new WeakReference<>(textView);
this.progressBar = new WeakReference<>(progressBar);
progressBar.setVisibility ( View.VISIBLE );
this.latLng = new WeakReference<>(latLng);
this.urlString = createGeocodeURL ();
}
private String createGeocodeURL ( ) {
String lat = Double.toString ( latLng.get ().latitude );
String lng = Double.toString ( latLng.get ().longitude );
return "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng +
"&key=" + context.get ().getString ( R.string.google_maps_key );
}
@Override
protected String doInBackground ( Void... params ) {
String result = "";
try {
URL url = new URL ( urlString );
HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection ();
httpsURLConnection.setReadTimeout ( 10000 );
httpsURLConnection.setConnectTimeout ( 15000 );
httpsURLConnection.setDoInput ( true );
httpsURLConnection.setRequestMethod ( "GET" );
httpsURLConnection.connect ();
int mStatus = httpsURLConnection.getResponseCode ();
if (mStatus == 200)
return readResponse ( httpsURLConnection.getInputStream () );
return result;
} catch (Exception e) {
e.printStackTrace ();
}
return null;
}
@Override
protected void onPostExecute ( String result ) {
super.onPostExecute ( result );
progressBar.get ().setVisibility ( View.GONE );
textView.get ().setText ( result );
progressBar.get ().setVisibility ( View.GONE );
}
private static String readResponse ( InputStream inputStream ) throws IOException, JSONException {
BufferedReader r = new BufferedReader ( new InputStreamReader ( inputStream ) );
StringBuilder stringBuilder = new StringBuilder ();
String line;
while ((line = r.readLine ()) != null) {
stringBuilder.append ( line );
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
return getAddress(jsonObject);
}
private static String getAddress ( JSONObject jsonObject ) {
String street_address = context.get ().getString (R.string.could_not_retrieve_location );
try {
String status = jsonObject.getString("status");
if(status.equalsIgnoreCase("OK")){
JSONArray results = jsonObject.getJSONArray("results");
int i = 0;
do{
JSONObject r = results.getJSONObject(i);
if(!r.getString("formatted_address").equalsIgnoreCase ( "" )){
street_address = r.getString("formatted_address");
break;
}
i++;
}while(i<results.length());
return street_address;
}
} catch (JSONException ignored) {
}
return street_address;
}
}
此代码将始终为您提供地址。验证
public class GeocodeLoader extends AsyncTask<Void, Void, String> {
private WeakReference<TextView> textView;
private WeakReference<ProgressBar> progressBar;
private WeakReference<LatLng> latLng;
private static WeakReference<Context> context;
private String urlString;
public GeocodeLoader ( Context context, LatLng latLng, TextView textView, ProgressBar progressBar) {
GeocodeLoader.context = new WeakReference<>(context);
this.textView = new WeakReference<>(textView);
this.progressBar = new WeakReference<>(progressBar);
progressBar.setVisibility ( View.VISIBLE );
this.latLng = new WeakReference<>(latLng);
this.urlString = createGeocodeURL ();
}
private String createGeocodeURL ( ) {
String lat = Double.toString ( latLng.get ().latitude );
String lng = Double.toString ( latLng.get ().longitude );
return "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng +
"&key=" + context.get ().getString ( R.string.google_maps_key );
}
@Override
protected String doInBackground ( Void... params ) {
String result = "";
try {
URL url = new URL ( urlString );
HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection ();
httpsURLConnection.setReadTimeout ( 10000 );
httpsURLConnection.setConnectTimeout ( 15000 );
httpsURLConnection.setDoInput ( true );
httpsURLConnection.setRequestMethod ( "GET" );
httpsURLConnection.connect ();
int mStatus = httpsURLConnection.getResponseCode ();
if (mStatus == 200)
return readResponse ( httpsURLConnection.getInputStream () );
return result;
} catch (Exception e) {
e.printStackTrace ();
}
return null;
}
@Override
protected void onPostExecute ( String result ) {
super.onPostExecute ( result );
progressBar.get ().setVisibility ( View.GONE );
textView.get ().setText ( result );
progressBar.get ().setVisibility ( View.GONE );
}
private static String readResponse ( InputStream inputStream ) throws IOException, JSONException {
BufferedReader r = new BufferedReader ( new InputStreamReader ( inputStream ) );
StringBuilder stringBuilder = new StringBuilder ();
String line;
while ((line = r.readLine ()) != null) {
stringBuilder.append ( line );
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
return getAddress(jsonObject);
}
private static String getAddress ( JSONObject jsonObject ) {
String street_address = context.get ().getString (R.string.could_not_retrieve_location );
try {
String status = jsonObject.getString("status");
if(status.equalsIgnoreCase("OK")){
JSONArray results = jsonObject.getJSONArray("results");
int i = 0;
do{
JSONObject r = results.getJSONObject(i);
if(!r.getString("formatted_address").equalsIgnoreCase ( "" )){
street_address = r.getString("formatted_address");
break;
}
i++;
}while(i<results.length());
return street_address;
}
} catch (JSONException ignored) {
}
return street_address;
}
}
谢谢你的帮助。好吧,我不想得到格式化的地址。我只想要单独的值路由
,街道号
,邮政编码
和国家
(总是长名称)。@user3475602在“好”编程中,你想要一个方法返回一个特定的对象,比如“getRoute()”或“getStreetNum()“,但是如果你想把所有的问题都放在一起,你可以这样做。我会用一个例子更新我的答案。非常感谢!祝你愉快!谢谢你的帮助。好吧,我不想得到格式化的地址
。我只想要单独的值路线
,街道号
,邮政编码
和国家
(始终为长名称)。@user3475602在“良好”编程中,您需要一个方法返回一个特定对象,如“getRoute()”或“getStreetNum()”,但是如果你想把所有的问题都放在一起,你可以这样做。我会用一个例子更新我的答案。非常感谢!祝你有愉快的一天!这个答案比6年前的好吗?嗨@stdunbar。经过分析,我发现,我们正在接收的JSON对象