android网络-GoogleMap之Json解析

Json解析相较其他解析方法来说,方法简单,效率较高

GoogleMap的Json源代码

{
   "results" : [
      {
         "address_components" : [
            {
               "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" : "中国天津市和平区滨江道",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 39.13263170,
                  "lng" : 117.21113880
               },
               "southwest" : {
                  "lat" : 39.11843570,
                  "lng" : 117.19430920
               }
            },
            "location" : {
               "lat" : 39.12642230,
               "lng" : 117.20112210
            },
            "location_type" : "GEOMETRIC_CENTER",
            "viewport" : {
               "northeast" : {
                  "lat" : 39.13263170,
                  "lng" : 117.21113880
               },
               "southwest" : {
                  "lat" : 39.11843570,
                  "lng" : 117.19430920
               }
            }
         },
         "types" : [ "route" ]
      }
   ],
   "status" : "OK"
}
程序效果:输入要查找的地点名称(通过对GoogleMap的Json解析,获取经纬度lng lat,从而得到地理坐标geoPoint,再把地理坐标转变为像素坐标point,继而绘制出标记图标),点击按钮,显示要查找的位置

主activity

package com.song;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class GoogleMapActivity extends MapActivity {
    /** Called when the activity is first created. */
	EditText edittext;
	Button button;
	MapView mapview; 
	
	MapController controller;
	GeoPoint geoPoint;
	Bitmap bitmap;
	
	double lng,lat;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        edittext=(EditText)findViewById(R.id.edittext);
        button=(Button)findViewById(R.id.button);
        mapview=(MapView)findViewById(R.id.mapview);
        bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.pos);//生成bitmap位图
   
        mapview.setBuiltInZoomControls(true);//实现放大缩小功能
        
        button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String url="http://maps.googleapis.com/maps/api/geocode/json?address="+edittext.getText().toString()+"&sensor=false";
				HttpClient client=new DefaultHttpClient();
				HttpGet get=new HttpGet(url);
				try {
					HttpResponse response=client.execute(get);
					HttpEntity entity=response.getEntity();
					InputStream input=entity.getContent();
					int t;
					StringBuffer buffer=new StringBuffer();
					while((t=input.read())!=-1)
					{
						buffer.append((char)t);
					}
					
					//json解析
					JSONObject object=new JSONObject(buffer.toString());
					JSONObject location=object
					.getJSONArray("results").getJSONObject(0)//获得中括号的内容
					.getJSONObject("geometry")//获得大括号中的内容
					.getJSONObject("location");
					lng=location.getDouble("lng");
					lat=location.getDouble("lat");
					
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
		   	    controller=mapview.getController();
		        geoPoint=new GeoPoint((int)(lat*1E6), (int)(lng*1E6));//注意参数是纬度,经度。E6为10的6次方
		        controller.animateTo(geoPoint);//定位到哪个点
		        //获得悬浮图层
		        List<Overlay> list = mapview.getOverlays();//获得MapView上原有的overlay对象
		        list.clear();//清除所有的overlay对象
		        list.add(new MyOverLay());//加新获取的overlay对象
			}
		});
        
    }
    class MyOverLay extends Overlay
	{  
		//画标记的方法
		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			// TODO Auto-generated method stub
			super.draw(canvas, mapView, shadow);
			Projection projection=mapView.getProjection();
			
			Point point=new Point();//定义输出的像素点
			projection.toPixels(geoPoint, point);//地理坐标转为像素坐标
			//绘制图片 
			//bitmap, left, top, paint
			canvas.drawBitmap(bitmap, point.x-(bitmap.getWidth()/2), point.y-(bitmap.getHeight()), null);
		} 
	}
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
}

布局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" >
<LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
   <EditText android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="请输入要定位的地点名称"
        android:layout_weight="8"
        android:id="@+id/edittext"/>
   <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="定位"
        android:layout_weight="2"
        android:id="@+id/button"/>
</LinearLayout>

   <com.google.android.maps.MapView
     android:id="@+id/mapview"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:clickable="true"
     android:apiKey="0HtSsgCEmiiTTfk-g0Oi59Wi2ndgjaMdoLSDPnw"
     />

</LinearLayout>

manifest

注意1,添加googlemap的类库<uses-library android:name="com.google.android.maps"/>

注意2,添加internet权限<uses-permission android:name="android.permission.INTERNET"/>


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.song"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".GoogleMapActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter> 
        </activity>
         <uses-library android:name="com.google.android.maps"/>
    </application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

显示效果


图标图片


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值