使用百度定位服务实现 GPS+基站+WI-FI+IP混合定位功能

经过测试,百度定位SDK提供了GPS+基站+WIFI+IP混合定位功能,传感器辅助定位,定位方式可自由切换,自动给出精度最好的定位结果。基站定位根据运营商的覆盖情况,精度达到100米-300米(我测的时候返回的精度是400米);WI-FI定位则能实现30-200米的精度。(我测的精度为35米);GPS定位能实现15-20米的精度(我测的精度为20米)

前提是先下载百度的定位SDK包和库文件,还有就是记得加上权限

http://blog.csdn.net/onlyonecoder/article/details/8464639这里是Android权限大全,附带说明,根据自己的需要添加吧


以下是全部代码:

main.xml


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


    <EditText
        android:id="@+id/locationinfo_et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_weight="0.2"
        android:hint="GPS+基站+WIFI+IP混合定位信息"
        />


    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/getlocation_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.33"
            android:text="开始定位" />

        <Button
            android:id="@+id/set_wifi_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.33"
            android:text="打开WIFI" />

        <Button
            android:id="@+id/set_gps_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.33"
            android:text="打开GPS" />
    </LinearLayout>

</LinearLayout>



Activity


import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

public class LocActivity extends Activity {
	private EditText locationinfo;// 基站定位信息
	private Button getlocation;// 定位按钮
	private Button set_wifi;// 设置wifi
	private Button set_gps;// 设置GPS

	private LocationClient mLocClient = null;// 定位类
	private boolean isOpenLocation = false;// 是否启动了定位API
	private Vibrator mVibrator01 = null;
	private WifiManager wifiManager;

	private LocationClientOption option = new LocationClientOption();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location);
		//实例化WifiManager
		wifiManager= (WifiManager) getSystemService(Context.WIFI_SERVICE);  
		
		
		locationinfo = (EditText) findViewById(R.id.locationinfo_et);
		getlocation = (Button) findViewById(R.id.getlocation_btn);
		set_wifi = (Button) findViewById(R.id.set_wifi_btn);
		set_gps = (Button) findViewById(R.id.set_gps_btn);

		// 实例化定位类
		mLocClient = ((Location) getApplication()).mLocationClient;
		((Location) getApplication()).mEt = locationinfo;
		mVibrator01 = (Vibrator) getApplication().getSystemService(
				Service.VIBRATOR_SERVICE);
		((Location) getApplication()).mVibrator01 = mVibrator01;

		getlocation.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				setLocationOption();
				mLocClient.start(); // 打开定位
				isOpenLocation = true; // 标识为已经打开了定位
				mLocClient.requestLocation();
			}
		});

		set_wifi.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				/*wifi状态
				 * WifiManager.WIFI_STATE_ENABLED//已开启
				 * WifiManager.WIFI_STATE_DISABLED//已关闭
				 * 
				 * WifiManager.WIFI_STATE_DISABLING//正在关闭
				 * WifiManager.WIFI_STATE_ENABLING//正在开启
				 * 
				 */
				if (wifiManager.getWifiState()==WifiManager.WIFI_STATE_ENABLED) {
					wifiManager.setWifiEnabled(true);
					Toast.makeText(LocActivity.this, "WIFI已经开启",
							Toast.LENGTH_SHORT).show();
				}
				// 当取消复选框选中状态时关闭WIFI
				else if(wifiManager.getWifiState()==WifiManager.WIFI_STATE_DISABLED){
//					wifiManager.setWifiEnabled(false);
					Toast.makeText(LocActivity.this, "WIFI设置成功,请重新定位!",
							Toast.LENGTH_SHORT).show();
//					wifistate = true;
				}else{
					Toast.makeText(LocActivity.this, "未知错误,请检查设备",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		set_gps.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				LocationManager alm = (LocationManager) LocActivity.this
						.getSystemService(Context.LOCATION_SERVICE);
				if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
					Toast.makeText(LocActivity.this, "GPS已经打开",
							Toast.LENGTH_SHORT).show();
				} else {
					Intent myIntent = new Intent(
							Settings.ACTION_SECURITY_SETTINGS);
					startActivityForResult(myIntent, 110);
				}

			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == 110) {
			option.setOpenGps(true);
			Toast.makeText(LocActivity.this, "设置 GPS成功,请重新定位",
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(LocActivity.this, "设置 GPS失败,请检查设备!",
					Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onDestroy() {
		mLocClient.stop();
		((Location) getApplication()).mEt = null;
		super.onDestroy();
	}

	// 设置相关参数
	private void setLocationOption() {

		// option.setOpenGps(mGpsCheck.isChecked()); //打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setAddrType("all"); // 设置地址信息,仅设置为“all”时有地址信息,默认无地址信息
		option.setScanSpan(Integer.parseInt("999")); // 设置定位模式,小于1秒则一次定位;大于等于1秒则定时定位
		mLocClient.setLocOption(option);
	}

}




Location类


import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.BDNotifyListener;

import android.app.Application;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Process;
import android.os.Vibrator;

public class Location extends Application {

	public LocationClient mLocationClient = null;
	private String mData;  
	public MyLocationListenner myListener = new MyLocationListenner();
	public EditText mEt;
	public NotifyLister mNotifyer=null;
	public Vibrator mVibrator01;
	
	@Override
	public void onCreate() {
		mLocationClient = new LocationClient(Location.this);
		mLocationClient.registerLocationListener( myListener );
		/**
		//如下3行代码为 位置提醒相关代码
		mNotifyer = new NotifyLister();
		mNotifyer.SetNotifyLocation(42.03249652949337,113.3129895882556,3000,"gps");//4个参数代表要位置提醒的点的坐标,具体含义依次为:纬度,经度,距离范围,坐标系类型(gcj02,gps,bd09,bd09ll)
		mLocationClient.registerNotify(mNotifyer);
		*/
		super.onCreate(); 
		Log.d("locSDK_Demo1", "... Application onCreate... pid=" + Process.myPid());
	}
	
	/**
	 * 显示字符串
	 * @param str
	 */
	public void logMsg(String str) {
		System.out.println("wawawawawawa");
		try {
			mData = str;
			if ( mEt != null )
				mEt.setText(mData);
			else
				mEt.setText("定位失败");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 监听函数,又新位置的时候,格式化成字符串,输出到屏幕中
	 */
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return ;
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation){
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
				sb.append("\n省:");
				sb.append(location.getProvince());
				sb.append("\n市:");
				sb.append(location.getCity());
				sb.append("\n区/县:");
				sb.append(location.getDistrict());
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
			}
			sb.append("\nsdk version : ");
			sb.append(mLocationClient.getVersion());
			logMsg(sb.toString());
		}
		
		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null){
				return ;
			}
			StringBuffer sb = new StringBuffer(256);
			sb.append("Poi time : ");
			sb.append(poiLocation.getTime());
			sb.append("\nerror code : ");
			sb.append(poiLocation.getLocType());
			sb.append("\nlatitude : ");
			sb.append(poiLocation.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(poiLocation.getLongitude());
			sb.append("\nradius : ");
			sb.append(poiLocation.getRadius());
			if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation){
				sb.append("\naddr : ");
				sb.append(poiLocation.getAddrStr());
			} 
			if(poiLocation.hasPoi()){
				sb.append("\nPoi:");
				sb.append(poiLocation.getPoi());
			}else{				
				sb.append("noPoi information");
			}
			logMsg(sb.toString());
		}
	}
	
	/**
	 * 位置提醒回调函数
	 */
	public class NotifyLister extends BDNotifyListener{
		public void onNotify(BDLocation mlocation, float distance){
			mVibrator01.vibrate(1000);
		}
	}
}



评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值