百度地图API使用之实现定位
1、初始化LocationClient类
/* * 此处需要注意:LocationClient类必须在主线程中声明。需要Context类型的参数。 * Context需要时全进程有效的context,推荐用getApplicationConext获取全进程有效的context */ public LocationClient mLocationClient = null; // BDLocationListener处理定位结果 // MyLocationListener实现两个方法:定位请求回调函数+poi请求回调函数 public BDLocationListener myListener = new MyLocationListener(); public void onCreate() { mLocationClient = new LocationClient(getApplicationContext()); //声明LocationClient类 mLocationClient.registerLocationListener( myListener ); //注册监听函数 }
2、实现BDLocationListener接口
/** * @author JL BDLocationListener接口有2个方法需要实现: * 1.接收异步返回的定位结果,参数是BDLocation类型参数。 * 2.接收异步返回的POI查询结果,参数是BDLocation类型参数。 */ public class MyLocationListener implements BDLocationListener { /* * 接收异步返回的定位结果 BDLocation包含详细的定位信息 */ @Override public void onReceiveLocation(BDLocation location) { // TODO Auto-generated method stub if (location == null) return; StringBuffer sb = new StringBuffer(256); sb.append("当前定位时间 : "); sb.append(location.getTime()); sb.append("\n获取定位类型 : "); sb.append(location.getLocType()); sb.append("\n纬度坐标 : "); sb.append(location.getLatitude()); sb.append("\n经度坐标 : "); sb.append(location.getLongitude()); sb.append("\n定位精度 : "); sb.append(location.getRadius()); if (location.getLocType() == BDLocation.TypeGpsLocation) { // 如果是GPS定位结果 sb.append("\n获取速度(仅gps定位) : "); sb.append(location.getSpeed()); sb.append("\n获取gps锁定用的卫星数 : "); sb.append(location.getSatelliteNumber()); sb.append("\n 获取手机当前的方向 : "); sb.append(location.getDirection()); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) { // 如果是网络定位结果 sb.append("\n获取详细地址信息: "); sb.append(location.getAddrStr()); sb.append("\n获取运营商信息 : "); sb.append(location.getOperators()); } GeoPoint geoPoint = new GeoPoint( (int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6)); // 将给定的位置点以动画形式移动至地图中心 mMapView.getController().animateTo(geoPoint); logMsg(sb.toString()); } // 接收异步返回的POI查询结果 @Override public void onReceivePoi(BDLocation arg0) { // TODO Auto-generated method stub } private void logMsg(String string) { // TODO Auto-generated method stub Log.i("MyLocationListener", string); } }
3、设置定位参数
LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationMode.Hight_Accuracy);//设置定位模式 option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02 option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms option.setIsNeedAddress(true);//返回的定位结果包含地址信息 option.setNeedDeviceDirect(true);//返回的定位结果包含手机机头的方向 mLocationClient.setLocOption(option); // 装在定位的属性 mLocationClient.setLocOption(option);
4、开始定位
// 启动定位sdk mLocationClient.start(); // 设置定位数据 if (mLocationClient != null && mLocationClient.isStarted()) // 请求定位,异步返回,结果在locationListener中获取. mLocationClient.requestLocation(); else Log.d(tag, "locClient is null or not started"); }
Done