Android使用百度地图SDK实现定位功能

来源:互联网 发布:淘宝企业店铺如何过户 编辑:程序博客网 时间:2024/06/05 16:07

这是嵌入式软件开发课程的一个选做作业:

1)使用google地图或百度地图,或者任意地图系统,获取当前所在经纬度位置,调用经纬度保存接口,保存到数据库中

2)从接口中读出最后一次保存的经纬度位置,在地图上标注显示出来

其中保存经纬度和取出上次保存的经纬度接口是由老师编写提供,可直接调用。


用到百度地图的SDK,需要有百度地图的密钥,可以去官网申请,还需要导入相关的包:



在AndroidManifest.xml 需要声明相关权限:


 <!-- 使用网络功能所需权限 -->    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.INTERNET" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >    </uses-permission>    <!-- SDK离线地图和cache功能需要读写外部存储器 -->    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >    </uses-permission>    <uses-permission android:name="android.permission.WRITE_SETTINGS" >    </uses-permission>    <!-- 获取设置信息和详情页直接拨打电话需要以下权限 -->    <uses-permission android:name="android.permission.READ_PHONE_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.CALL_PHONE" >    </uses-permission>    <!-- 使用定位功能所需权限,demo已集成百度定位SDK,不使用定位功能可去掉以下6项 -->    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >    </uses-permission>    <permission android:name="android.permission.BAIDU_LOCATION_SERVICE" >    </permission>    <uses-permission android:name="android.permission.BAIDU_LOCATION_SERVICE" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_GPS" />

密钥在application标签下声明:

<meta-data            android:name="com.baidu.lbsapi.API_KEY"            android:value="uAhNx95XRMBK8FCDoZB3utZw" ></meta-data>

声明定位服务:

<service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote" />


 MapActivity主要代码如下,在代码中有相应的注释:

    private BMapManager mBMapMan = null;    //地图视图     private MapView mMapView = null;    //定位客户端    private LocationClient mLocationClient = null;    //位置图层    private MyLocationOverlay myOverlay;    //位置在图层中的索引    private int myOverlayIndex = 0;    //是否定位到我的位置    private boolean bmyLocal = true;        private SaveAsyncRequest saveRequest;    private GetLastPosAsyncRequest getLastPosRequest;    private double currentLatitude = 0.0;    private double currentLongitude = 0.0;      @Override      protected void onCreate(Bundle savedInstanceState){        super.onCreate(savedInstanceState);        //在setContentView之前必须先初始化百度地图        mBMapMan = new BMapManager(getApplicationContext());        //mBMapMan.init(null);        mBMapMan.init(new MyGeneralListener());                 //ע在试用setContentView前初始化BMapManager对象        setContentView(R.layout.activity_main);            mMapView=(MapView)findViewById(R.id.bmapsView);            //设置启用内置的缩放控件         mMapView.setBuiltInZoomControls(true);            // 得到mMapView的控制权,可以用它控制和驱动平移和缩放          MapController mMapController=mMapView.getController();            mMapController.setZoom(12);//设置地图zoom级别                   //定位功能代码开始         mLocationClient = new LocationClient(this);        //mLocationClient.setAccessKey(BD_KEY);                myOverlay = new MyLocationOverlay(mMapView);        //myOverlay.enableCompass();        LocationClientOption option = new LocationClientOption();        option.setLocationMode(LocationMode.Hight_Accuracy);//高精度        option.setCoorType("bd0911");//返回的定位结果是百度经纬度,默认值gcj02            option.setIsNeedAddress(true);//返回的定位结果包含地址信息        option.setNeedDeviceDirect(true);                mLocationClient.setLocOption(option);               //注册位置监听        mLocationClient.registerLocationListener(locationListener);        if(mLocationClient!=null&&!mLocationClient.isStarted())          {              mLocationClient.requestLocation();              mLocationClient.start();          }          else              Log.e("LocSDK4", "locClient is null or not started");            }        private BDLocationListener locationListener = new BDLocationListener(){        @Override        public void onReceiveLocation(BDLocation location) {            // TODO Auto-generated method stub            Dispose(location);        }        @Override        public void onReceivePoi(BDLocation location) {            // TODO Auto-generated method stub            Dispose(location);        }                private void Dispose(BDLocation location){             if (location == null)                 return ;            //需要定位到我的位置?             if(bmyLocal)               {                   Toast.makeText(MapActivity.this, "正在定位",                         Toast.LENGTH_LONG).show();                 currentLatitude=location.getLatitude();                   currentLongitude=location.getLongitude();                   LocationData data=new LocationData();                   data.latitude=currentLatitude;                   data.longitude=currentLongitude;                   data.direction=2.0f;                   myOverlay.setData(data);                  //检查覆盖物是否存在,存在则修改,否则则添加                 if(mMapView.getOverlays().contains(myOverlay))                   {                       mMapView.getOverlays().set(myOverlayIndex,myOverlay);                   }                   else{                       myOverlayIndex=mMapView.getOverlays().size();                       mMapView.getOverlays().add(myOverlay);                    }                                                         GeoPoint geoPoint=new GeoPoint((int)(currentLatitude* 1E6),(int)(currentLongitude* 1E6));                                   mMapView.getController().setCenter(geoPoint);                  mMapView.refresh();                   bmyLocal=false;                  //Log.i("定位信息:",sb.toString());              }                        }            };        //创建菜单      @Override      public boolean onCreateOptionsMenu(Menu menu)      {           //组、ID、排序、菜单名          menu.add(0,1,1,"我的位置");          menu.add(0,2,1,"保存位置");        menu.add(0,3,1,"上次保存位置");        menu.add(0,4,1, "注销");                return true;      }         //处理菜单    @Override      public boolean onOptionsItemSelected(MenuItem item)      {          Intent intent = getIntent();        String strUserNumber = intent.getStringExtra("strUserNumber");        String strSession = intent.getStringExtra("strSession");        switch(item.getItemId())          {                case 1:  //我的位置                      bmyLocal=true;                       //如果客户端定位服务已经启动过了,则直接发起定位请求                        if(mLocationClient!=null&&mLocationClient.isStarted()){                       mLocationClient.requestLocation();                       }else{                         //启动定位服务,启动的时候会自动发起定位请求,默认为requestLocation                           mLocationClient.start();                           }                       break;             case 2:  //保存位置                     //System.out.println(strUserNumber + "----" + strSession);                     if(getLastPosRequest!=null){                         getLastPosRequest.cancel(true);                     }                     Toast.makeText(MapActivity.this, "正在保存当前位置",                             Toast.LENGTH_SHORT).show();                     saveRequest = new SaveAsyncRequest();                     saveRequest.execute(strUserNumber,strSession);                     break;            case 3: //上次位置                    if(saveRequest!=null){                        saveRequest.cancel(true);                    }                    Toast.makeText(MapActivity.this, "正在定位上次保存位置",                            Toast.LENGTH_LONG).show();                    getLastPosRequest = new GetLastPosAsyncRequest();                    getLastPosRequest.execute(strUserNumber,strSession);                    break;            case 4: //注销                    finish();        }          return true;      }   

定位的默认图标是一个蓝色的小圆圈,在定位上次保存位置的时候,如果还是原来的图标的话,不是很直观,所以找了办法改了一下默认的图标:

     double lastLongitude = Double.parseDouble(result.get(2));     double lastLatitude = Double.parseDouble(result.get(3));     GeoPoint lastPosition = new GeoPoint((int) (lastLatitude * 1E6), (int) (lastLongitude * 1E6));       Drawable mark= getResources().getDrawable(R.drawable.icon_gcoding);     OverlayItem item1 = new OverlayItem(lastPosition, "item1", "item1");     item1.setMarker(mark);     ItemizedOverlay<OverlayItem> itemizedOverlay = new ItemizedOverlay<OverlayItem>(mark, mMapView);     //mMapView.getOverlays().clear();     mMapView.getOverlays().add(itemizedOverlay);     itemizedOverlay.addItem(item1);     mMapView.getController().animateTo(lastPosition);     mMapView.refresh();

界面运行效果如下:

定位当前位置和定位上次保存位置

         



0 0
原创粉丝点击