1. 程式人生 > 其它 >Android Stdio 百度地圖定位作業BLOG

Android Stdio 百度地圖定位作業BLOG

技術標籤:android studio

配置環境與許可權

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mybaidulcoate">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2,
but you must specify either coarse or fine location permissions for the 'MyLocation' functionality. --> <!-- 這個許可權用於進行網路定位--> <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卡讀取許可權,使用者寫入離線定位資料--> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <!-- The API key for Google Maps-based APIs is defined as a string resource. (See the file "res/values/google_maps_api.xml"). Note that the API key is linked to the encryption key used to sign the APK. You need a different API key for each encryption key, including the release key that is used to sign the APK for publishing. You can define the keys for the debug and release targets in src/debug/ and src/release/. --> <meta-data android:name="com.baidu.lbsapi.API_KEY" android:value="1e9jt4o5grtzivBwkUfcMePi59y6zehS"> </meta-data> <service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote"></service> <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    public LocationClient mLocationClient;
    public BDLocationListener myListener = new MyLocationListener();
    private Button bt;
    private Button button;
    private Button buttons;
    private LatLng latLng;
    private boolean isFirstLoc = true; // 是否首次定位

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        initView();
        initMap();
    }


    private void initMap() {
        //獲取地圖控制元件引用
        mBaiduMap = mMapView.getMap();
        //普通地圖
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setMyLocationEnabled(true);

        //預設顯示普通地圖
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        // 開啟定點陣圖層
        mBaiduMap.setMyLocationEnabled(true);
        mLocationClient = new LocationClient(getApplicationContext());     //宣告LocationClient類
        //配置定位SDK引數
        initLocation();
        mLocationClient.registerLocationListener(myListener);    //註冊監聽函式
        //開啟定位
        mLocationClient.start();
        //圖片點選事件,回到定位點
        mLocationClient.requestLocation();
    }

    //配置定位SDK引數
    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有效時按照1S/1次頻率輸出GPS結果
        option.setIsNeedLocationDescribe(true);//可選,預設false,設定是否需要位置語義化結果,可以在BDLocation
        // .getLocationDescribe裡得到,結果類似於“在北京天安門附近”
        option.setIsNeedLocationPoiList(true);//可選,預設false,設定是否需要POI結果,可以在BDLocation.getPoiList裡得到
        option.setIgnoreKillProcess(false);
        option.setOpenGps(true); // 開啟gps

        //可選,預設true,定位SDK內部是一個SERVICE,並放到了獨立程序,設定是否在stop的時候殺死這個程序,預設不殺死
        option.SetIgnoreCacheException(false);//可選,預設false,設定是否收集CRASH資訊,預設收集
        option.setEnableSimulateGps(false);//可選,預設false,設定是否需要過濾GPS模擬結果,預設需要
        mLocationClient.setLocOption(option);
    }

    //實現BDLocationListener介面,BDLocationListener為結果監聽介面,非同步獲取定位結果
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            latLng = new LatLng(location.getLatitude(),location.getLongitude());
            // 構造定位資料
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此處設定開發者獲取到的方向資訊,順時針0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            // 設定定位資料
            mBaiduMap.setMyLocationData(locData);
            // 當不需要定點陣圖層時關閉定點陣圖層
            //mBaiduMap.setMyLocationEnabled(false);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                if (location.getLocType() == BDLocation.TypeGpsLocation) {
                    // GPS定位結果
                    Toast.makeText(MainActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                    // 網路定位結果
                    Toast.makeText(MainActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();

                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                    // 離線定位結果
                    Toast.makeText(MainActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();

                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    Toast.makeText(MainActivity.this, "伺服器錯誤,請檢查", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    Toast.makeText(MainActivity.this, "網路錯誤,請檢查", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    Toast.makeText(MainActivity.this, "手機模式錯誤,請檢查是否飛行", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void initView() {
        mMapView = (MapView) findViewById(R.id.bmapView);
        bt = (Button) findViewById(R.id.bt);
        bt.setOnClickListener(this);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
        buttons = (Button) findViewById(R.id.buttons);
        buttons.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命週期管理
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity執行onResume時執行mMapView. onResume (),實現地圖生命週期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity執行onPause時執行mMapView. onPause (),實現地圖生命週期管理
        mMapView.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt:
                //把定位點再次顯現出來
                MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(latLng);
                mBaiduMap.animateMapStatus(mapStatusUpdate);
                break;
            case R.id.button:
                //衛星地圖
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.buttons:
                //普通地圖
                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                break;
        }
    }
}

結果展示:
在這裡插入圖片描述
在這裡插入圖片描述

碼雲:https://gitee.com/yang-desheng/MybaiduLocate