第四十五天 百度地圖定位SDK

定位SDK同地圖SDK步驟一樣,密鑰也一樣,由於包可能不同,所以得到的key也可能不同

MapActivity:

public class MapActivity extends Activity {
    private Button mButton;//找到某一點
    private Button mButtonOwn;//定位自己
    private Button mButtonLine;//畫線,連接兩個點
    private MapView mapView;
    GeoCoder mSearch = null;
    BaiduMap mBaiduMap = null;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    private  List<LatLng> points = new ArrayList<LatLng>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        mLocationClient = new LocationClient(getApplicationContext());     //聲明LocationClient類
        mLocationClient.registerLocationListener(myListener);    //註冊監聽函數
        setContentView(R.layout.activity_map);
        mButton = (Button) findViewById(R.id.button);
        mButtonOwn = (Button) findViewById(R.id.button_own);
        mButtonLine= (Button) findViewById(R.id.button_line);
        mapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mapView.getMap();

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSearch.geocode(new GeoCodeOption().city("北京").address("海淀區中關村北京大學"));
            }
        });
        mButtonOwn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initLocation();
                mLocationClient.start();
            }
        });
        mButtonLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OverlayOptions ooPolyline = new PolylineOptions().width(10)
                        .color(0xAAFF0000).points(points);
                mBaiduMap.addOverlay(ooPolyline);
            }
        });

        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(MapActivity.this, "抱歉,未能找到結果", Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                mBaiduMap.clear();
                mBaiduMap.addOverlay(new MarkerOptions().position(geoCodeResult.getLocation())
                        .icon(BitmapDescriptorFactory
                                .fromResource(R.mipmap.egl)));
                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(geoCodeResult
                        .getLocation()));
                String strInfo = String.format("緯度:%f 經度:%f",
                        geoCodeResult.getLocation().latitude, geoCodeResult.getLocation().longitude);
                Log.d("strInfo", strInfo);
                Toast.makeText(MapActivity.this, strInfo, Toast.LENGTH_LONG).show();
                LatLng point1=new LatLng(geoCodeResult.getLocation().latitude, geoCodeResult.getLocation().longitude);
                points.add(point1);//添加第一個點
            }
            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
            }
        });
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可選,默認高精度,設置定位模式,高精度,低功耗,僅設備
        option.setCoorType("bd09ll");//可選,默認gcj02,設置返回的定位結果座標系
        int span = 1000;
        option.setScanSpan(span);//可選,默認0,即僅定位一次,設置發起定位請求的間隔需要大於等於1000ms纔是有效的
        option.setIsNeedAddress(true);//可選,設置是否需要地址信息,默認不需要
        option.setOpenGps(true);//可選,默認false,設置是否使用gps
        option.setLocationNotify(true);//可選,默認false,設置是否當gps有效時按照1S1次頻率輸出GPS結果
        option.setIsNeedLocationDescribe(true);//可選,默認false,設置是否需要位置語義化結果,可以在BDLocation.getLocationDescribe裏得到,結果類似於“在北京天安門附近”
        option.setIsNeedLocationPoiList(true);//可選,默認false,設置是否需要POI結果,可以在BDLocation.getPoiList裏得到
        option.setIgnoreKillProcess(false);//可選,默認false,定位SDK內部是一個SERVICE,並放到了獨立進程,設置是否在stop的時候殺死這個進程,默認殺死
        option.SetIgnoreCacheException(false);//可選,默認false,設置是否收集CRASH信息,默認收集
        option.setEnableSimulateGps(false);//可選,默認false,設置是否需要過濾gps仿真結果,默認需要
        mLocationClient.setLocOption(option);
    }
    class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            LatLng point2=new LatLng(location.getLatitude(),location.getLongitude());
            mBaiduMap.addOverlay(new MarkerOptions().position(point2)
                    .icon(BitmapDescriptorFactory
                            .fromResource(R.mipmap.egl)));
            mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point2));
            points.add(point2);//添加第二個點
            //Receive Location
            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) {// GPS定位結果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 單位:公里每小時
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 單位:米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 單位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 網絡定位結果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                //運營商信息
                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號和大體定位時間到[email protected],會有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("網絡不同導致定位失敗,請檢查網絡是否通暢");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("無法獲取有效定位依據導致定位失敗,一般是由於手機的原因,處於飛行模式下一般會造成這種結果,可以試着重啓手機");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置語義化信息
            List<Poi> list = location.getPoiList();// POI數據
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            Log.i("BaiduLocationApiDem", sb.toString());
            mLocationClient.stop();
        }
    }
}

AndroidManifest.xml:

<!-- 這個權限用於進行網絡定位-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <!-- 這個權限用於訪問GPS定位-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
    <!-- 用於訪問wifi網絡信息,wifi信息會用於進行網絡定位-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <!-- 獲取運營商信息,用於支持提供運營商信息相關的接口-->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <!-- 這個權限用於獲取wifi的獲取權限,wifi信息會用來進行網絡定位-->
    <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" />
    <!-- SD卡讀取權限,用戶寫入離線定位數據-->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
...
//(寫在application內)
<service
            android:name="com.baidu.location.f"
            android:enabled="true"
            android:process=":remote">
        </service>
        <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="MtPu4RVf4s12ANV1BEYaFiaY"/>

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章