、簡單實現百度地圖實時定位功能

首先是在百度地圖官網註冊賬戶,然後進行申請api,其他就不囉嗦了,獲取sha1碼方法

參考如下文章  http://jingyan.baidu.com/article/a681b0de0f860f3b184346bc.html

上代碼

public class MainActivity extends AppCompatActivity {
    MapView mapView;
    // TODO: 2017-06-21 獲取實時定位
    BaiduMap baiduMap;
    LocationManager locationmanger;
    private String provider;
    private boolean isFirstlocats = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //獲取sdk的值,進行初始化,調用getApplicationContext獲取全局傳入
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        mapView = (MapView) findViewById(R.id.map_view);
        //獲取baidumap實例
        baiduMap = mapView.getMap();
        // TODO: 2017-06-21 修改實現本人位置顯示
        baiduMap.setMyLocationEnabled(true);
        //獲取位置提供器
        locationmanger = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //獲取所有位置提供器
        //獲取所有可用的額位置提供器
        List<String> providerlist = locationmanger.getProviders(true);
        if (providerlist.contains(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (providerlist.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else {
            //當前沒有可用的位置提供器
            Toast.makeText(this, "當前沒有可用的位置提供器", Toast.LENGTH_SHORT).show();
            return;
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationmanger.getLastKnownLocation(provider);
        if (location != null) {
            //顯示當前設備位置信息
            showlocation(location);
        }
        locationmanger.requestLocationUpdates(provider, 5000, 1, locationlistener);
    }


    LocationListener locationlistener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            //更新當前位置信息
            if (location != null) {
                Log.e("jknhkhnj", "lkklmkl");
                showlocation(location);
            }

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };


    private void showlocation(final Location locationmessage) {
        if (isFirstlocats) {
//            String currentposition = "經度  :" + locationmessage.getLatitude() + "\n" + "緯度 :" + locationmessage.getLongitude();
//            Log.e("currentposition", "===" + currentposition);
            LatLng ll = new LatLng(locationmessage.getLatitude(), locationmessage.getLongitude());
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(update);
            update = MapStatusUpdateFactory.zoomBy(16f);
            baiduMap.animateMapStatus(update);
            isFirstlocats = false;
        }
        // TODO: 2017-06-21 添加修改實現本人位置顯示
        MyLocationData.Builder locationbuilder = new MyLocationData.Builder();
        locationbuilder.latitude(locationmessage.getLatitude());
        locationbuilder.longitude(locationmessage.getLongitude());
        MyLocationData locationData = locationbuilder.build();
        baiduMap.setMyLocationData(locationData);
    }

    @Override
    protected void onDestroy() {
        //activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命週期管理
        super.onDestroy();
        // TODO: 2017-06-21 增加顯示個人位置
        baiduMap.setBaiduHeatMapEnabled(false);
        mapView.onDestroy();
        if (locationmanger != null) {
            //關閉程序時候監聽器移除
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            locationmanger.removeUpdates(locationlistener);
        }
    }

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

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

-===================================================================
需要給build.gradle中添加如下代碼
/**
 * 目前 Android Studio不支持自動添加 .so文件(Eclipse是支持的),所以我們需要手動加載libs下的.so的動態庫
 */
sourceSets {
    main() {
        jniLibs.srcDirs = ['libs']
    }
}
==============================================
權限問題
//百度地圖的權限
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<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" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
==================================================
注意
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    //百度地圖的設置
    <meta-data
        android:name="com.baidu.lbsapi.API_KEY"
        android:value="pPcy7cpMIxvofYKRiCItv6BpwrvTZG1s" />
</application>


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