調用百度地圖實現在地圖上定位

   下面我說說在百度地圖上實現定位。

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.platform.comapi.basestruct.GeoPoint;


public class MainActivity extends Activity {
	private TextView mTv = null;
	public LocationClient mLocationClient = null;
	public MyLocationListenner myListener = new MyLocationListenner();
	public Button ReLBSButton=null;
	public static String TAG = "msg";
	
	BMapManager mBMapMan = null;
	MapView mMapView = null;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//地圖
		mBMapMan=new BMapManager(getApplication());
    	mBMapMan.init(null); 
		
		setContentView(R.layout.activity_main);
		
		//地圖
		mMapView=(MapView)findViewById(R.id.bmapsView);
    	mMapView.setBuiltInZoomControls(true);  //實現放大縮小地圖的功能
    	mMapView.setTraffic(true);     //顯示交通狀況
    	//mMapView.setSatellite(true);   //顯示衛星地圖
    	MapController mMapController=mMapView.getController();
		// 得到mMapView的控制權,可以用它控制和驅動平移和縮放
		GeoPoint point =new GeoPoint((int)(39.915* 1E6),(int)(116.404* 1E6));
		//用給定的經緯度構造一個GeoPoint,單位是微度 (度 * 1E6)
    	mMapController.setCenter(point);//設置地圖中心點
    	mMapController.setZoom(12);//設置地圖zoom級別
		
		
		mTv = (TextView)findViewById(R.id.textview);
		ReLBSButton=(Button)findViewById(R.id.ReLBS_button);
		
		mLocationClient = new LocationClient( getApplicationContext() );

		/**——————————————————————————————————————————————————————————————————
		 * 這裏的AK和應用簽名包名綁定,如果使用在自己的工程中需要替換爲自己申請的Key
		 * ——————————————————————————————————————————————————————————————————
		 */
//		mLocationClient.setAK("697f50541f8d4779124896681cb6584d");	 
//		mLocationClient.setAK("z4nqERrqxnhNzT5VOGNVRt80");
		mLocationClient.registerLocationListener( myListener );

		setLocationOption();//設定定位參數
		
		mLocationClient.start();//開始定位
System.out.println(1);
		
		// 重新定位
		ReLBSButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mLocationClient != null && mLocationClient.isStarted()){
					mLocationClient.requestLocation();
System.out.println(3);			}	
				else
					Log.d("msg", "locClient is null or not started");
			}
		});
		
	} 
	
	//設置相關參數
	private void setLocationOption(){
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");//返回的定位結果包含地址信息
		option.setCoorType("bd09ll");//返回的定位結果是百度經緯度,默認值gcj02
		option.setScanSpan(50000);//設置發起定位請求的間隔時間爲5000ms
		option.disableCache(true);//禁止啓用緩存定位
		option.setPoiNumber(5);    //最多返回POI個數   
		option.setPoiDistance(1000); //poi查詢距離        
		option.setPoiExtraInfo(true); //是否需要POI的電話和地址等詳細信息        
		mLocationClient.setLocOption(option);
		
	} 

	@Override
	public void onDestroy() {
		mLocationClient.stop();//停止定位
		 mMapView.destroy();
         if(mBMapMan!=null){
                 mBMapMan.destroy();
                 mBMapMan=null;
         }
		mTv = null;
		super.onDestroy();
	}


	/**
	 * 監聽函數,有更新位置的時候,格式化成字符串,輸出到屏幕中
	 */
	public class MyLocationListenner implements BDLocationListener {
		@Override
		//接收位置信息
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return ;
			StringBuffer sb = new StringBuffer(256);
			sb.append("1時間 : ");
			sb.append(location.getTime());
			sb.append("\n1return code : ");
			sb.append(location.getLocType());
			sb.append("\n1latitude : ");
			sb.append(location.getLatitude());
			sb.append("\n1lontitude : ");
			sb.append(location.getLongitude());
			sb.append("\n1radius : ");
			sb.append(location.getRadius());
System.out.println(2);
			if (location.getLocType() == BDLocation.TypeGpsLocation){
				sb.append("\n2speed : ");
				sb.append(location.getSpeed());
				sb.append("\n2satellite : ");
				sb.append(location.getSatelliteNumber());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
				/**
				 * 格式化顯示地址信息
				 */
				sb.append("\n3addr : ");
				sb.append(location.getAddrStr());
			}
			sb.append("\n4sdk version : ");
			sb.append(mLocationClient.getVersion());
			sb.append("\n4isCellChangeFlag : ");
			sb.append(location.isCellChangeFlag());
			mTv.setText(sb.toString());
			Log.i(TAG, sb.toString()); 
	mMapView.getController().setCenter(new GeoPoint((int)(29.52* 1E6), (int)(106.57* 1E6)));
	//mMapView.getController().setZoom(12);
	mMapView.refresh();
		}
		//接收POI信息函數,我不需要POI,所以我沒有做處理
		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}


}

在這段代碼裏我沒有進行實時定位,只是給地圖傳了一個經緯度在地圖上顯示而已,東西弄的比較水,看看效果吧


上面是定位的經緯度想,下面是地圖。記住百度定位sdk4.0以上要申請密鑰才能使用,還有,密鑰不是在程序裏給定而是在manifest文件中給定 <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="HP3YeKaxrdwZzZCDHC5sR6lo" />

下面給出manifest文件吧

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
         <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="HP3YeKaxrdwZzZCDHC5sR6lo" />
        <activity
            android:name="com.example.bdgps.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         <service
            android:name="com.baidu.location.f"
            android:enabled="true"
            android:process=":remote" >
        </service>
    </application>
    
    
    
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
    </uses-permission>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" >
    </uses-permission>
    <uses-permission android:name="android.permission.READ_LOGS" >
    </uses-permission>
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />

</manifest>













在.xml文件中記得定義好mapview,下面給出.xml文件

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

    <TextView 
         android:id="@+id/textview"
        android:layout_width="194dp"
        android:layout_height="wrap_content"
        />
    <Button
        android:id="@+id/ReLBS_button"
        android:layout_width="194dp"
        android:layout_height="wrap_content"
        android:text="Update My Location" />
    
    
     <com.baidu.mapapi.map.MapView android:id="@+id/bmapsView"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:clickable="true" />

        
</LinearLayout>


源碼下載:http://download.csdn.net/detail/u011833422/7221291

發佈了22 篇原創文章 · 獲贊 2 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章