Android位置服务——百度LBS

通常定位有两种方法——GPS和网络定位

  • 手机GPS定位在室内信号差,不推荐。【不需要网络就能定位】
  • 网络定位的原理时根据手机网络附近的三个基站测速,从而获得手机到基站的举例,这种方法精确度一般。【但国内没法用Google API】

所以一般用百度或高德的API来使用定位功能

一、申请百度API key

1、注册

非商用是不收费的,注册使用地址,注册激活需要手机号和邮箱,待会在邮箱还要验证
Android位置服务——百度LBS_第1张图片
然后在控制台这里输入应用名【我的应用是day19_LBSTest】,类型选Android SDK
Android位置服务——百度LBS_第2张图片

2、SHA1指纹

打开Android Studio右侧工具窗口栏的Gradle,依次打开项目名appTasksandroidsigningReport
Android位置服务——百度LBS_第3张图片
双击signingReport,就能查看签名文件信息,里面就有SHA1指纹,不过这个指纹是debug.keystore文件【用于测试的签名文件】的指纹,把这个暂时填写在两个输入框就行。
Android位置服务——百度LBS_第4张图片
不过在应用发布时就必须要正式的签名文件了,如果要得到正式签名文件的指纹需要在控制台输入以及正确的密码:

keytool -list v --keystore <签名文件路径>

最后点击提交,这里的AK就是申请到的API Key
Android位置服务——百度LBS_第5张图片

二、使用百度定位

新建一个空项目day19_LBSTest

1、准备LBS SDK

【下载地址】,选择 “基础定位” 和 “基础地图” 够了,再点击 “开发包” 下载
Android位置服务——百度LBS_第6张图片
下载解压后进入,进入libs目录,能看到:
Android位置服务——百度LBS_第7张图片
其中BaiduLBS_Android.jarJAVA层用到的,其他so文件Native层用到的。

接下来将文件复制到项目对应目录:

  1. BaiduLBS_Android.jar放到app/libs目录下
  2. 展开app/src/main目录,新建jniLibs目录,把其他目录放到这里

Android位置服务——百度LBS_第8张图片

2、确定自己的经纬度

布局:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/position_text_view"/>

LinearLayout>

权限:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.day19_lbstest">

    
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <application
        android:usesCleartextTraffic="true"
        android:requestLegacyExternalStorage="true"
        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"
        tools:targetApi="q">
        <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="填写申请到的key"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.LAUNCHER" />
            intent-filter>
        activity>
        <service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote"> service>
    application>

manifest>

主活动:

  1. 创建LocationClient实例,传入全局Context
  2. 用实例注册定位监听器.registerLocationListener(),传入一个继承BDAbstractLocationListener的监听器
  3. 依次检查三大授权
  4. 开始定位实例.start(),监听器方法onReceiveLocation()会被回调
public class MainActivity extends AppCompatActivity {
    public LocationClient mLocationClient;
    private TextView positionText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        positionText = findViewById(R.id.position_text_view);
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
        } else {
            requstLocation();
        }
    }

    private void requstLocation() {
        mLocationClient.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    for (int result : grantResults) {
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(this, "权限呢???", Toast.LENGTH_SHORT).show();
                            finish();
                            return;
                        }
                    }
                    requstLocation();
                } else {
                    Toast.makeText(this, "未知错误!", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                break;
        }
    }

    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(final BDLocation bdLocation) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    StringBuilder currentPosition = new StringBuilder();
                    currentPosition.append("纬度:").append(bdLocation.getLatitude()).append("\n");
                    currentPosition.append("经线:").append(bdLocation.getLongitude()).append("\n");
                    currentPosition.append("定位方式:");
                    if (bdLocation.getLocType() == BDLocation.TypeGpsLocation) {
                        currentPosition.append("GPS");
                    } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
                        currentPosition.append("网络");
                    }
                    positionText.setText(currentPosition);
                }
            });
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            super.onConnectHotSpotMessage(s, i);
        }
    }
}

运行:
Android位置服务——百度LBS_第9张图片
增加实时定位:.setScanSpan()设置刷新间隔

...
    private void requstLocation() {
        initLocation();
        mLocationClient.start();
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(5000);
        mLocationClient.setLocOption(option);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
    }
....

强制使用GPS定位:

option.setLocationMode(LocationClientOption.LocationMode.Device_sensors);

3、看懂位置信息

......
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(5000);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
    }
......
				public void run() {
                    StringBuilder currentPosition = new StringBuilder();
                    currentPosition.append("纬度:").append(bdLocation.getLatitude()).append("\n");
                    currentPosition.append("经线:").append(bdLocation.getLongitude()).append("\n");
                    currentPosition.append("国家:").append(bdLocation.getCountry()).append("\n");
                    currentPosition.append("省份:").append(bdLocation.getProvince()).append("\n");
                    currentPosition.append("市:").append(bdLocation.getCity()).append("\n");
                    currentPosition.append("区:").append(bdLocation.getDistrict()).append("\n");
                    currentPosition.append("街道:").append(bdLocation.getStreet()).append("\n");
                    currentPosition.append("定位方式:");
                    if (bdLocation.getLocType() == BDLocation.TypeGpsLocation) {
                        currentPosition.append("GPS");
                    } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
                        currentPosition.append("网络");
                    }
                    positionText.setText(currentPosition);
                }
                
......

Android位置服务——百度LBS_第10张图片

三、使用百度地图

1、显示地图

修改布局:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/position_text_view"
        android:visibility="gone"/>
    
    <com.baidu.mapapi.map.MapView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/bmapView"
        android:clickable="true"/>

LinearLayout>

修改活动:

public class MainActivity extends AppCompatActivity {
......
    private MapView mapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
......
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        mapView = findViewById(R.id.bmapView);
   }
......

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        mapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }
}

【一定要注意:setContentView()要在SDKInitializer.initialize()之后,在findViewById(R.id.bmapView)之前】
运行:
Android位置服务——百度LBS_第11张图片
但是不晓得为啥报这个错,不过报这个错没啥影响:
Android位置服务——百度LBS_第12张图片

2、移动到一个位置

  1. 创建BaiduMap实例作为控制器:mapView.getMap()
  2. 设置缩放【取值3~19】:实例.animateMapStatus(MapStatusUpdataFactory.zoomTi(12.5f))
  3. 创建LatLng类设置经纬度:实例.animateMapStatus(MapStatusUpdateFactory.newLatlng(new LatLng(39.915, 116.404)))
public class MainActivity extends AppCompatActivity {
......
    private BaiduMap baiduMap;
    private boolean isFirstLocate = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);

        mapView = findViewById(R.id.bmapView);
        baiduMap = mapView.getMap();

        ......
    }


    private void navigateTo(BDLocation location){
        if (isFirstLocate){
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(update);
            update = MapStatusUpdateFactory.zoomTo(16f);
            baiduMap.animateMapStatus(update);
            isFirstLocate = false;
        }
    }

    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(final BDLocation bdLocation) {
            if(bdLocation.getLocType() == BDLocation.TypeGpsLocation || bdLocation.getLocType() == BDLocation.TypeNetWorkLocation){
                navigateTo(bdLocation);
            }
    }

3、将自己显示在地图上

MyLocationData.Build类将经纬度传进去就可以了:

MyLocationData.Builder locationBuilder = new MyLocationData.Builder();
locationBuilder.latitude(39.666);
locationBuilder.longitude(116.444);

接着调用.build(),就会生成MylocationData实例,再将这个实例传入BaiduMap.setMyLocationData(),就可以让设备位置显示到地图上了

MylocationData locationData = locationBuilder.build();
baiduMap.setMyLocationData(locationData);

比如:

public class MainActivity extends AppCompatActivity {
......
    private BaiduMap baiduMap;
    private boolean isFirstLocate = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        mapView = findViewById(R.id.bmapView);
        baiduMap = mapView.getMap();
        baiduMap.setMyLocationEnabled(true);
    }

    private void navigateTo(BDLocation location){
        if (isFirstLocate){
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(update);
            update = MapStatusUpdateFactory.zoomTo(16f);
            baiduMap.animateMapStatus(update);
            isFirstLocate = false;
        }
        MyLocationData.Builder builder = new MyLocationData.Builder();
        builder.latitude(location.getLatitude());
        builder.longitude(location.getLongitude());
        MyLocationData locationData = builder.build();
        baiduMap.setMyLocationData(locationData);
    }

......
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        mapView.onDestroy();
        baiduMap.setMyLocationEnabled(false);
    }

}

记得要先setMyLocationEnabled()打开,在程序退出时再关闭。

你可能感兴趣的:(第二行代码,android,安卓,移动开发)