基础定位功能代码实现
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="包名">
<!-- 访问网络 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 获取访问手机振动器权限,用于导航过程中的震动提示 -->
<uses-permission android:name="android.permission.VIBRATE"/>
<!-- 获取摄像头权限,用于AR步行导航 -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_GPS"/>
<!-- 网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<!-- 获取网络状态,根据网络状态切换进行数据请求网络转换 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<!-- 读取外置存储。如果开发者使用了so动态加载功能并且把so文件放在了外置存储区域,则需要申请该权限,否则不需要 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- 写外置存储。如果开发者使用了离线地图,并且数据写在外置存储区域,则需要申请该权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!--允许应用读取低级别的系统日志文件 -->
<uses-permission android:name="android.permission.READ_LOGS"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:name=".utils.SDKInitApplication"
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">
<!-- 2.2.在Application标签中声明定位的service组件 -->
<service android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote"/>
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="百度地图AKey"/>
<activity android:name=".DemoListActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".location.LocationActivity" />
</application>
</manifest>
LocationActivity.java
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import java.util.ArrayList;
import java.util.List;
public class LocationActivity extends AppCompatActivity {
protected MapView mMapView = null;
protected BaiduMap mBaiduMap;
public LocationClient locationClient = null;
public MyLocationListener myLocationListener = new MyLocationListener();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取地图控件引用
mMapView = findViewById(R.id.bmapView);
mBaiduMap = mMapView.getMap(); //获取地图控制器
//设置地图缩放为15
MapStatusUpdate mapStatusUpdate2 = MapStatusUpdateFactory.zoomTo(18);
mBaiduMap.setMapStatus(mapStatusUpdate2);
//获取地图UI控制器,隐藏指南针
UiSettings uiSettings = mBaiduMap.getUiSettings();
uiSettings.setCompassEnabled(false); //不显示指南针
//动态申请权限
List<String> permissionList = new ArrayList<>();
if (ContextCompat.checkSelfPermission(LocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (ContextCompat.checkSelfPermission(LocationActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.READ_PHONE_STATE);
}
if (ContextCompat.checkSelfPermission(LocationActivity.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(LocationActivity.this, permissions, 1);
}
locationClient = new LocationClient(getApplicationContext());
//注册监听函数
locationClient.registerLocationListener(myLocationListener);
initLocationOption();
//开启定位图层
mBaiduMap.setMyLocationEnabled(true);
MyLocationConfiguration.LocationMode mode = MyLocationConfiguration.LocationMode.COMPASS;
boolean enableDirection = true;
BitmapDescriptor customMarker = new BitmapDescriptorFactory().fromResource(R.drawable.icon_marka);
MyLocationConfiguration myLocationConfiguration = new MyLocationConfiguration(mode, enableDirection, customMarker);
mBaiduMap.setMyLocationConfiguration(myLocationConfiguration);
//开始定位
locationClient.start();
}
@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
protected void onDestroy() {
super.onDestroy();
locationClient.unRegisterLocationListener(myLocationListener);
locationClient.stop(); //停止定位
//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mMapView.onDestroy();
}
/**
* 初始化定位参数配置
*/
private void initLocationOption() {
//声明LocationClient类实例并配置定位参数
LocationClientOption locationOption = new LocationClientOption();
//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选,默认gcj02,设置返回的定位结果坐标系,如果配合百度地图使用,建议设置为bd09ll;
locationOption.setCoorType("bd09ll");
//可选,默认0,即仅定位一次,设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
locationOption.setScanSpan(5000);
//可选,设置是否需要地址信息,默认不需要
locationOption.setIsNeedAddress(true);
//可选,设置是否需要地址描述
locationOption.setIsNeedLocationDescribe(true);
//可选,设置是否需要设备方向结果
locationOption.setNeedDeviceDirect(false);
//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果
locationOption.setLocationNotify(true);
//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
locationOption.setIgnoreKillProcess(true);
//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
locationOption.setIsNeedLocationDescribe(true);
//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
locationOption.setIsNeedLocationPoiList(true);
//可选,默认false,设置是否收集CRASH信息,默认收集
locationOption.SetIgnoreCacheException(false);
//可选,默认false,设置是否开启Gps定位
locationOption.setOpenGps(true);
//可选,默认false,设置定位时是否需要海拔信息,默认不需要,除基础定位版本都可用
locationOption.setIsNeedAltitude(false);
//设置打开自动回调位置模式,该开关打开后,期间只要定位SDK检测到位置变化就会主动回调给开发者,该模式下开发者无需再关心定位间隔是多少,定位SDK本身发现位置变化就会及时回调给开发者
locationOption.setOpenAutoNotifyMode();
//设置打开自动回调位置模式,该开关打开后,期间只要定位SDK检测到位置变化就会主动回调给开发者
locationOption.setOpenAutoNotifyMode(3000, 1, LocationClientOption.LOC_SENSITIVITY_HIGHT);
//需将配置好的LocationClientOption对象,通过setLocOption方法传递给LocationClient对象使用
locationClient.setLocOption(locationOption);
}
/**
* 实现定位回调
*/
public class MyLocationListener extends BDAbstractLocationListener {
/**
* 定位请求回调函数
*
* @param location 定位结果
*/
@Override
public void onReceiveLocation(BDLocation location) {
// TODO Auto-generated method stub
if (location != null) {
MyLocationData.Builder builder = new MyLocationData.Builder();
builder.accuracy(location.getRadius());
builder.direction(location.getDirection());
builder.latitude(location.getLatitude());
builder.longitude(location.getLongitude());
MyLocationData locationData = builder.build();
mBaiduMap.setMyLocationData(locationData);
StringBuffer sb = new StringBuffer(256);
sb.append("\ntime : ");
sb.append(location.getTime());
sb.append("\nlocType : ");// 定位类型
sb.append(location.getLocType());
sb.append("\nlocType description : ");// *****对应的定位类型说明*****
sb.append(location.getLocTypeDescription());
sb.append("\nlatitude : ");// 纬度
sb.append(location.getLatitude());
sb.append("\nlongtitude : ");// 经度
sb.append(location.getLongitude());
sb.append("\nradius : ");// 半径
sb.append(location.getRadius());
sb.append("\nCountryCode : ");// 国家码
sb.append(location.getCountryCode());
sb.append("\nProvince : ");// 获取省份
sb.append(location.getProvince());
sb.append("\nCountry : ");// 国家名称
sb.append(location.getCountry());
sb.append("\ncitycode : ");// 城市编码
sb.append(location.getCityCode());
sb.append("\ncity : ");// 城市
sb.append(location.getCity());
sb.append("\nDistrict : ");// 区
sb.append(location.getDistrict());
sb.append("\nStreet : ");// 街道
sb.append(location.getStreet());
sb.append("\naddr : ");// 地址信息
sb.append(location.getAddrStr());
sb.append("\nStreetNumber : ");// 获取街道号码
sb.append(location.getStreetNumber());
sb.append("\nUserIndoorState: ");// *****返回用户室内外判断结果*****
sb.append(location.getUserIndoorState());
sb.append("\nDirection(not all devices have value): ");
sb.append(location.getDirection());// 方向
if (location.getLocType() == BDLocation.TypeGpsLocation) { //GPS定位结果
sb.append("\nspeed: ");
sb.append(location.getSpeed());
sb.append("\ngetSatelliteNumber: ");
sb.append(location.getSatelliteNumber());
sb.append("\nheight: ");
sb.append(location.getAltitude());
sb.append("\ngetDirection: ");
sb.append(location.getDirection());
sb.append("\naddr: ");
sb.append(location.getAddrStr());
sb.append("\ndescription ");
sb.append("gps定位成功");
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
// 运营商信息
if (location.hasAltitude()) {// *****如果有海拔高度*****
sb.append("\nheight : ");
sb.append(location.getAltitude());// 单位:米
}
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号和大体定位时间到loc-bugs@baidu.com,会有人追查原因");
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
sb.append("\ndescribe : ");
sb.append("网络不同导致定位失败,请检查网络是否通畅");
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
sb.append("\ndescribe : ");
sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机");
}
sb.append("\nlocationDescription");
sb.append(location.getLocationDescribe()); //位置语义化信息
List<Poi> list = location.getPoiList();
if (list != null) {
sb.append("\npoilist size = :");
sb.append(list.size());
for (Poi poi : list) {
sb.append("\npoi= :");
sb.append(poi.getId() + "" + poi.getName() + "" + poi.getRank());
}
}
Log.i("BaiDuLocationDemo", sb.toString());
}
}
}
}
SDKInitApplication.java
import android.app.Application;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
public class SDKInitApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//在使用SDK各组件之前初始化context信息,传入ApplicationContext
SDKInitializer.initialize(this);
//自4.3.0起,百度地图SDK所有接口均支持百度坐标和国测局坐标,用此方法设置您使用的坐标类型.
//包括BD09LL和GCJ02两种坐标,默认是BD09LL坐标。
SDKInitializer.setCoordType(CoordType.BD09LL);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true" />
</androidx.constraintlayout.widget.ConstraintLayout>
icon_marka.png