
学习目的
1.地理信息JSON数据的解析
2.利用所学的JSON知识和向WEB程序发送请求,获得我们想要的位置的地理信息。
JSON地理信息数据
案例7:利用发送请求的方式获得JSON地理信息数据并对数据进行解析 -主要代码
1. //发送请求下载JSON
2. public static String getJSONFromURL(String url){
3. String result = "";
4. HttpClient client = null;
5. client = new DefaultHttpClient(null);
6. HttpPost post = new HttpPost(url);
7. try {
8. //设置请求头的语言为中文简体
9. post.setHeader("accept-language", "zh-cn");
10. HttpResponse response = client.execute(post);
11. HttpEntity entity = response.getEntity();
12. result = EntityUtils.toString(entity, "UTF-8");
13. } catch (Exception e) {
14. e.printStackTrace();
15. }
16. returnresult;
17. }
18. //JSON数据的封装对象
19. public class GsonData {
20. publicString status;
21. publicList<Result> results;
22. }
23. // Geometry对象
24. public class Geometry {
25. public Location location;
26. }
27. //Location对象
28. public class Location {
29. public double lat;
30. public double lng;
31. }
32. //Result对象
33. public class Result {
34. public List<Address_components> address_components;
35. public Geometry geometry;
36. public String[] types;
37. public String formatted_address;
38. }
39. // Address_components对象
40. public class Address_components {
41. publicString long_name;
42. publicString short_name;
43. publicString[] types;
44. }
45. btn.setOnClickListener(new View.OnClickListener() {//按钮点击事件
46. @Override
47. public void onClick(View v) {
48. String url ="http://maps.google.com/maps/api/geocode/json? sensor=false®ion=cn&address=";
49. url = url + txt.getText();
50. String s = Utils.getJSONFromURL(url);
51. Gsongson = new Gson();
52. GsonData data = gson.fromJson(s, GsonData.class); // 解析JSON
53. if (data.status.equals("OK") && data.results.size() > 0) {
54. Toast.makeText(GPSJSONDemoActivity.this,
55. data.results.get(0).formatted_address+ "纬度:"+date.result.get(0).geometry.
location.lat+"经度:"
56. +data.results.get(0).geometry.location.lng,
57. Toast.LENGTH_LONG).show();
58. }else{
59. Toast.makeText(GPSJSONDemoActivity.this, "无此位置的信息", Toast.LENGTH_SHORT).show
();}}
60. });}
同步训练与考核评价
本项目的“同步训练”考核评价内容如表所示:
“同步训练”考核评价表
