# BaiduLocDemo **Repository Path**: BaiDuMapSDK/baidulocdemo ## Basic Information - **Project Name**: BaiduLocDemo - **Description**: 百度定位官方Demo - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2017-06-26 - **Last Updated**: 2022-08-31 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README #BDLocation各属性 # ``` BDLocation location ``` |名称|说明|值| |--|--|--| |getTime()|服务端出本次结果的时间,如果位置不发生变化,则时间不变|| |getLocType()|定位类型|| |getLocTypeDescription()|定位类型说明|| |getLatitude()|纬度|| |getLongitude()|经度|| |getRadius()|半径|| |getCountryCode()|国家码|| |getCountry()|国家名称|| |getCityCode()|城市编码|| |getCity()|城市|| |getDistrict()|区|| |getStreet()|街道|| |getAddrStr()|地址信息|| |getUserIndoorState()|用户室内外判断结果|| |getDirection()|方向|| |getLocationDescribe()|位置语义化信息|| ``` if (null != location && location.getLocType() != BDLocation.TypeServerError) { StringBuffer sb = new StringBuffer(256); sb.append("time : "); /** * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来,每次回调的时间; * location.getTime() 是指服务端出本次结果的时间,如果位置不发生变化,则时间不变 */ sb.append(location.getTime()); sb.append("\nlocType : ");// 定位类型 sb.append(location.getLocType()); sb.append("\nlocType description : ");// *****对应的定位类型说明***** sb.append(location.getLocTypeDescription()); sb.append("\nlatitude : ");// 纬度 sb.append(location.getLatitude()); sb.append("\nlontitude : ");// 经度 sb.append(location.getLongitude()); sb.append("\nradius : ");// 半径 sb.append(location.getRadius()); sb.append("\nCountryCode : ");// 国家码 sb.append(location.getCountryCode()); sb.append("\nCountry : ");// 国家名称 sb.append(location.getCountry()); sb.append("\ncitycode : ");// 城市编码 sb.append(location.getCityCode()); sb.append("\ncity : ");// 城市 sb.append(location.getCity()); sb.append("\nDistrict : ");// 区 sb.append(location.getDistrict()); sb.append("\nStreet : ");// 街道 sb.append(location.getStreet()); sb.append("\naddr : ");// 地址信息 sb.append(location.getAddrStr()); sb.append("\nUserIndoorState: ");// *****返回用户室内外判断结果***** sb.append(location.getUserIndoorState()); sb.append("\nDirection(not all devices have value): "); sb.append(location.getDirection());// 方向 sb.append("\nlocationdescribe: "); sb.append(location.getLocationDescribe());// 位置语义化信息 sb.append("\nPoi: ");// POI信息 if (location.getPoiList() != null && !location.getPoiList().isEmpty()) { for (int i = 0; i < location.getPoiList().size(); i++) { Poi poi = (Poi) location.getPoiList().get(i); sb.append(poi.getName() + ";"); } } if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果 sb.append("\nspeed : "); sb.append(location.getSpeed());// 速度 单位:km/h sb.append("\nsatellite : "); sb.append(location.getSatelliteNumber());// 卫星数目 sb.append("\nheight : "); sb.append(location.getAltitude());// 海拔高度 单位:米 sb.append("\ngps status : "); sb.append(location.getGpsAccuracyStatus());// *****gps质量判断***** sb.append("\ndescribe : "); sb.append("gps定位成功"); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果 // 运营商信息 if (location.hasAltitude()) {// *****如果有海拔高度***** sb.append("\nheight : "); sb.append(location.getAltitude());// 单位:米 } sb.append("\noperationers : ");// 运营商信息 sb.append(location.getOperators()); sb.append("\ndescribe : "); sb.append("网络定位成功"); } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果 sb.append("\ndescribe : "); sb.append("离线定位成功,离线定位结果也是有效的"); } else if (location.getLocType() == BDLocation.TypeServerError) { sb.append("\ndescribe : "); sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因"); } else if (location.getLocType() == BDLocation.TypeNetWorkException) { sb.append("\ndescribe : "); sb.append("网络不同导致定位失败,请检查网络是否通畅"); } else if (location.getLocType() == BDLocation.TypeCriteriaException) { sb.append("\ndescribe : "); sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机"); } logMsg(sb.toString()); Log.d(TAG, "地址:" + location.getAddrStr()); } ``` # 官方基础定位demo # Demo: https://git.oschina.net/BaiDuMapSDK/baidulocdemo > 创建类`LocationService`,在Application中创建`LocationService`对象,在需要定位的activity中注册监听和开启定位。 ## LocationService ## `LocationService`不是`Service`,就是一个工具类。 ``` public class LocationService { private LocationClient client = null; private LocationClientOption mOption,DIYoption; private Object objLock = new Object(); /*** * * @param locationContext */ public LocationService(Context locationContext){ synchronized (objLock) { if(client == null){ client = new LocationClient(locationContext); client.setLocOption(getDefaultLocationClientOption()); } } } /*** * * @param listener * @return */ public boolean registerListener(BDLocationListener listener){ boolean isSuccess = false; if(listener != null){ client.registerLocationListener(listener); isSuccess = true; } return isSuccess; } public void unregisterListener(BDLocationListener listener){ if(listener != null){ client.unRegisterLocationListener(listener); } } /*** * * @param option * @return isSuccessSetOption */ public boolean setLocationOption(LocationClientOption option){ boolean isSuccess = false; if(option != null){ if(client.isStarted()) client.stop(); DIYoption = option; client.setLocOption(option); } return isSuccess; } public LocationClientOption getOption(){ return DIYoption; } /*** * * @return DefaultLocationClientOption */ public LocationClientOption getDefaultLocationClientOption(){ if(mOption == null){ mOption = new LocationClientOption(); mOption.setLocationMode(LocationMode.Hight_Accuracy);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 mOption.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系,如果配合百度地图使用,建议设置为bd09ll; mOption.setScanSpan(3000);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的 mOption.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要 mOption.setIsNeedLocationDescribe(true);//可选,设置是否需要地址描述 mOption.setNeedDeviceDirect(false);//可选,设置是否需要设备方向结果 mOption.setLocationNotify(false);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 mOption.setIgnoreKillProcess(true);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 mOption.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近” mOption.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 mOption.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集 mOption.setIsNeedAltitude(false);//可选,默认false,设置定位时是否需要海拔信息,默认不需要,除基础定位版本都可用 } return mOption; } public void start(){ synchronized (objLock) { if(client != null && !client.isStarted()){ client.start(); } } } public void stop(){ synchronized (objLock) { if(client != null && client.isStarted()){ client.stop(); } } } public boolean requestHotSpotState(){ return client.requestHotSpotState(); } } ``` ## LocationApplication ## ``` public class LocationApplication extends Application { public LocationService locationService; @Override public void onCreate() { super.onCreate(); locationService = new LocationService(getApplicationContext()); } } ``` ## 在Activity中使用 ## ``` public class LocationActivity extends Activity { private LocationService locationService; private Button startLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.location); } @Override protected void onStop() { locationService.unregisterListener(mListener); //注销掉监听 locationService.stop(); //停止定位服务 super.onStop(); } @Override protected void onStart() { super.onStart(); //获取locationservice实例,建议应用中只初始化1个location实例,然后使用,可以参考其他示例的activity,都是通过此种方式获取locationservice实例的 locationService = ((LocationApplication) getApplication()).locationService; locationService.registerListener(mListener); startLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { locationService.start(); startLocation.setText(getString(R.string.stoplocation)); } }); } /***** * * 定位结果回调,重写onReceiveLocation方法,可以直接拷贝如下代码到自己工程中修改 * */ private BDLocationListener mListener = new BDLocationListener() { @Override public void onReceiveLocation(BDLocation location) { // TODO Auto-generated method stub if (null != location && location.getLocType() != BDLocation.TypeServerError) { ... } } public void onConnectHotSpotMessage(String s, int i) { } }; } ``` # 定位的功能模块 # 百度定位官方Demo实现的功能: - 判断当前是wifi还是移动热点 - 位置震动提醒 ## 判断当前是wifi还是移动热点 ## 类型: ``` LocationClient.CONNECT_HOT_SPOT_FALSE:0,不是移动热点 LocationClient.CONNECT_HOT_SPOT_TRUE:1,是移动热点 LocationClient.CONNECT_HOT_SPOT_UNKNOWN:-1,连接状态未知 ``` 先要设置请求热点类型 ``` client.requestHotSpotState(); ``` 在回调中判断 ``` class MyLocationListener implements BDLocationListener{ @Override public void onConnectHotSpotMessage(String connectWifiMac, int hotSpotState) { String resT; if(hotSpotState == 0){ resText = "不是移动, wifi:"+connectWifiMac; } else if(hotSpotState == 1){ resText = "是wifi热点, wifi:"+connectWifiMac; } else if (hotSpotState == -1){ resText = "未连接wifi"; } res.setText(resText); } @Override public void onReceiveLocation(BDLocation arg0) { // TODO Auto-generated method stub } } ``` ## 位置提醒 ## 先获取震动的类Vibrator` ``` Vibrator mVibrator =(Vibrator)getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE); ``` 注册位置提醒监听即可。 ``` NotifyLister mNotifyLister = new NotifyLister(); mLocationClient.registerNotify(mNotifyLister); ``` ``` public class NotifyLister extends BDNotifyListener{ public void onNotify(BDLocation mlocation, float distance){ mVibrator.vibrate(1000);//振动提醒已到设定位置附近 } } ``` 同时在位置监听中还需要设置提醒点的坐标 ``` public class NotiftLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { longtitude = location.getLongitude(); latitude = location.getLatitude(); notifyHandler.sendEmptyMessage(0); } public void onConnectHotSpotMessage(String s, int i){ } } ``` (为什么要在Handler中处理?) ``` private Handler notifyHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); mNotifyLister.SetNotifyLocation(latitude,longtitude, 3000,mLocationClient.getLocOption().getCoorType()); //4个参数代表要位置提醒的点的坐标,具体含义依次为:纬度,经度,距离范围,坐标系类型(gcj02,gps,bd09,bd09ll) } }; ``` 关闭提醒 ``` mLocationClient.removeNotifyEvent(mNotifyLister); ```