通常定位有两种方法——GPS和网络定位
所以一般用百度或高德的API来使用定位功能
API key
非商用是不收费的,注册使用地址,注册激活需要手机号和邮箱,待会在邮箱还要验证
然后在控制台这里输入应用名【我的应用是day19_LBSTest
】,类型选Android SDK
SHA1
指纹打开Android Studio右侧工具窗口栏的Gradle
,依次打开项目名
→ app
→ Tasks
→ android
→ signingReport
双击signingReport
,就能查看签名文件信息,里面就有SHA1
指纹,不过这个指纹是debug.keystore
文件【用于测试的签名文件】的指纹,把这个暂时填写在两个输入框就行。
不过在应用发布时就必须要正式的签名文件了,如果要得到正式签名文件的指纹需要在控制台输入以及正确的密码:
keytool -list v --keystore <签名文件路径>
新建一个空项目
day19_LBSTest
LBS SDK
【下载地址】,选择 “基础定位” 和 “基础地图” 够了,再点击 “开发包” 下载
下载解压后进入,进入libs
目录,能看到:
其中BaiduLBS_Android.jar
是JAVA
层用到的,其他so文件
是Native
层用到的。
接下来将文件复制到项目对应目录:
BaiduLBS_Android.jar
放到app/libs
目录下app/src/main
目录,新建jniLibs
目录,把其他目录放到这里布局:
<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>
主活动:
LocationClient
实例,传入全局Context
.registerLocationListener()
,传入一个继承BDAbstractLocationListener
的监听器实例.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);
}
}
}
运行:
增加实时定位:.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);
......
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);
}
......
修改布局:
<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)
之前】
运行:
但是不晓得为啥报这个错,不过报这个错没啥影响:
BaiduMap
实例作为控制器:mapView.getMap()
实例.animateMapStatus(MapStatusUpdataFactory.zoomTi(12.5f))
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);
}
}
用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()
打开,在程序退出时再关闭。