当前位置: 代码迷 >> JavaScript >> 谷歌map根据经纬度确定地点-JSON解析
  详细解决方案

谷歌map根据经纬度确定地点-JSON解析

热度:208   发布时间:2012-08-25 10:06:20.0
谷歌地图根据经纬度确定地点---JSON解析

JSON解析分为以下几个步骤

1.下载url上的所有的json数据

package mars.com;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpDownloader {
	// 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容
	// 1.创建一个URL对象
	// 2.通过URL对象,创建一个HttpURLConnection对象
	// 3.得到InputStream
	// 4.从InputStream当中读取数据
	private URL url;

	public String download(String urlStr) {
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try {
			url = new URL(urlStr);
			HttpURLConnection urlConn = (HttpURLConnection) url
					.openConnection();
			buffer = new BufferedReader(new InputStreamReader(
					urlConn.getInputStream()));
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				buffer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}

2.
package mars.com;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class DemoMapJSONActivity extends Activity {
	private Button button;
	private TextView show;
	private EditText longitude;
	private EditText latitude;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		button = (Button) findViewById(R.id.location);
		show = (TextView) findViewById(R.id.show);
		longitude = (EditText) findViewById(R.id.longitude);
		latitude = (EditText) findViewById(R.id.latitude);
		button.setOnClickListener(new MyLocationListener());

	}

	class MyLocationListener implements OnClickListener {
		public void onClick(View v) {
			HttpDownloader HTT = new HttpDownloader();
			String strUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng="
					+ latitude.getText().toString()
					+ ","
					+ longitude.getText().toString()
					+ "&sensor=false&language=zh-CN";
			String jsonData = HTT.download(strUrl);

			StringBuffer buf = new StringBuffer();
			try {
				Map<String, Object> result = parseJson(jsonData);

				List<Map<String, Object>> all = (List<Map<String, Object>>) result
						.get("results");
				Iterator<Map<String, Object>> iterator = all.iterator();
				int i = 0;
				while (iterator.hasNext()) {
					Map<String, Object> map = iterator.next();
					buf.append("\n地址:" + map.get("formatted_address")
							+ "*********" + i++);
					break;
				}
				Map<String, Object> address_components = parseJson(jsonData);
				List<Map<String, Object>> all2 = (List<Map<String, Object>>) address_components
						.get("address_components");
				Iterator<Map<String, Object>> iterator2 = all2.iterator();
				int j = 0;
				while (iterator2.hasNext()) {
					Map<String, Object> map = iterator2.next();
					buf.append("\n地址:" + map.get("long_name") + "*********"
							+ j++);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			show.setText(buf);
		}
	}

	private Map<String, Object> parseJson(String data) throws Exception {
		Map<String, Object> allMap = new HashMap<String, Object>();
		JSONObject allData = new JSONObject(data);// 全部的内容变为一个项
		JSONArray jsonArray = allData.getJSONArray("results");// 取出数组
		List<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> all2 = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < jsonArray.length(); i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			map.put("formatted_address",
					jsonObject.getString("formatted_address"));
			all.add(map);
			if (i != 0) {
				continue;
			}// 只取出第一组完整数据,其他的都没这组详细
			JSONArray jsonArray2 = jsonObject
					.getJSONArray("address_components");
			for (int j = 0; j < jsonArray2.length(); j++) {
				Map<String, Object> map2 = new HashMap<String, Object>();
				JSONObject jsonObject3 = jsonArray2.getJSONObject(j);
				map2.put("long_name", jsonObject3.get("long_name"));
				all2.add(map2);
				System.out.println("****");
			}

		}
		allMap.put("results", all);// 所有的取出的简直对的list,放到results底下了
		allMap.put("address_components", all2);
		return allMap;
	}

}
3.main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/longitude"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="114.3579530" />

    <EditText
        android:id="@+id/latitude"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="30.6096780" />

    <Button
        android:id="@+id/location"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="定位" />

    <TextView
        android:id="@+id/show"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="显示" />

</LinearLayout>

4.配置权限

<uses-permission android:name="android.permission.INTERNET" />

怕有些人看不懂代码,在此说明以下,我这里只是解析的我需要的最详细地址,其实这个json已经足够复杂了,但是我实际上是经过偷工减料的,我只取了最详细的一组数据

以及最详细的分组数据。所以没有用到工具类。

本来应该用工具类来着,比如说里面的results应该单独是一个类才行,但是我没有用他的其他的属性,所以没有详细的解析。

如果想使用它的其他的属性,比如说address_components,formatted_address ,geometry,types。那你得详细的把这个类的结构写出来,然后以键值对的形式放到List中,然后你想取哪个数据都可以了,就看你了。

json数据如下

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "1178号",
               "short_name" : "1178号",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "和平大道",
               "short_name" : "和平大道",
               "types" : [ "route" ]
            },
            {
               "long_name" : "武昌区",
               "short_name" : "武昌区",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "武汉",
               "short_name" : "武汉",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "湖北省",
               "short_name" : "湖北省",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "中国",
               "short_name" : "CN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "中国湖北省武汉市武昌区和平大道1178号",
         "geometry" : {
            "location" : {
               "lat" : 30.61071999999999,
               "lng" : 114.3566410
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 30.61206898029149,
                  "lng" : 114.3579899802915
               },
               "southwest" : {
                  "lat" : 30.60937101970850,
                  "lng" : 114.3552920197085
               }
            }
         },
         "types" : [ "street_address" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "武昌区",
               "short_name" : "武昌区",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "武汉",
               "short_name" : "武汉",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "湖北省",
               "short_name" : "湖北省",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "中国",
               "short_name" : "CN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "中国湖北省武汉市武昌区",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 30.62807880,
                  "lng" : 114.42031060
               },
               "southwest" : {
                  "lat" : 30.49578920,
                  "lng" : 114.26042410
               }
            },
            "location" : {
               "lat" : 30.5538990,
               "lng" : 114.3158970
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 30.62807880,
                  "lng" : 114.42031060
               },
               "southwest" : {
                  "lat" : 30.49578920,
                  "lng" : 114.26042410
               }
            }
         },
         "types" : [ "sublocality", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "武汉",
               "short_name" : "武汉",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "湖北省",
               "short_name" : "湖北省",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "中国",
               "short_name" : "CN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "中国湖北省武汉市",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 31.36126030,
                  "lng" : 115.08257280
               },
               "southwest" : {
                  "lat" : 29.96907670,
                  "lng" : 113.70228110
               }
            },
            "location" : {
               "lat" : 30.5930870,
               "lng" : 114.3053570
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 30.78745989999999,
                  "lng" : 114.6189880
               },
               "southwest" : {
                  "lat" : 30.34877210,
                  "lng" : 113.9817810
               }
            }
         },
         "types" : [ "locality", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "湖北省",
               "short_name" : "湖北省",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "中国",
               "short_name" : "CN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "中国湖北省",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 33.27561610,
                  "lng" : 116.13484340
               },
               "southwest" : {
                  "lat" : 29.02948840,
                  "lng" : 108.36696460
               }
            },
            "location" : {
               "lat" : 30.5458610,
               "lng" : 114.3419210
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 33.27561610,
                  "lng" : 116.13484340
               },
               "southwest" : {
                  "lat" : 29.02948840,
                  "lng" : 108.36696460
               }
            }
         },
         "types" : [ "administrative_area_level_1", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "中国",
               "short_name" : "CN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "中国",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 53.56097399999999,
                  "lng" : 134.772810
               },
               "southwest" : {
                  "lat" : 18.15352160,
                  "lng" : 73.49941369999999
               }
            },
            "location" : {
               "lat" : 35.861660,
               "lng" : 104.1953970
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 53.56097399999999,
                  "lng" : 134.772810
               },
               "southwest" : {
                  "lat" : 18.15352160,
                  "lng" : 73.49941369999999
               }
            }
         },
         "types" : [ "country", "political" ]
      }
   ],
   "status" : "OK"
}


  相关解决方案