作业要求
根据官方文档,开发百度地图定位App,显示出当前位置坐标。
实现过程
1、注册和获取密钥
根据官方文档获取密钥,参考网址:https://lbsyun.baidu.com/index.php?title=androidsdk/guide/create-project/ak#threeanchor
2、Android Studio配置
同样根据官方文档来进行配置,参考网址:https://lbsyun.baidu.com/index.php?title=androidsdk/guide/create-map/showmap
说明:
红框中的“开发者 key”就是你获取的AK,我的AK:yp3Xdo8eybFqG7C41vjA2HYi52tUTvog
3、显示地图与定位
(1)新建一个自定义的Application,在其onCreate方法中完成SDK的初始化:
public class Myapplication extends Application {
@Override
public void onCreate() {
super.onCreate();
SDKInitializer.initialize(this);
SDKInitializer.setCoordType(CoordType.BD09LL);
}
}
(2)新建一个MainAcitivity.java文件,管理MapView生命周期:
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy() {
mLocationClient.stop();
baiduMap.setMyLocationEnabled(false);
mapView.onDestroy();
mapView = null;
super.onDestroy();
}
(3)新建一个MyLocationListener.Java文件,通过继承抽象类BDAbstractListener并重写其onReceieveLocation方法来获取定位数据,并将其传给MapView:
public void onReceiveLocation(BDLocation location) {
if (location == null || mapView== null){
return;
}
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
.direction(location.getDirection()).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
baiduMap.setMyLocationData(locData);
}
(4)在MainAcitivity.java文件中通过LocationClient发起定位:
mLocationClient = new LocationClient(this);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);
option.setCoorType("bd09ll");
option.setScanSpan(1000);
mLocationClient.setLocOption(option);
MyLocationListener myLocationListener = new MyLocationListener(mapView,baiduMap);
mLocationClient.registerLocationListener(myLocationListener);
mLocationClient.start();
效果展示:
作业源码:
https://gitee.com/czyxioawu/AppLBS.git
|