简介
借助百度地图 api 实现地图功能
LBS
基于位置的服务简称 LBS,获取用户的位置有两种方式: GPS定位,网络定位;
GPS 定位基于手机内置的 GPS 硬件直接和卫星交互获取当前的经纬度,这种方式精确度非常高,但是只适合室外使用,室内无法接收到信号;
网络定位是根据手机当前网络附近的三个基站进行测速,以此计算出手机和每个基站的距离,然后通过三个点确定圆心得到位置,这种方式精确度一般,但是适用于室内外;
申请 API Key
这个 demo 是利用百度地图的接口去实现一个内嵌的地图功能,那么首先需要做的就是去申请百度的 API key,这样才能调用到百度地图的 API。
利用百度地图的 API 进行开发
初始化
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.registerLocationListener(new MyLocationListener());
LocationClientOption option = new LocationClientOption();
option.setScanSpan(5000);
option.setIsNeedAddress(true);
mLocationClient.setLocOption(option);
mLocationClient.start();
获取位置信息
public class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation bdLocation) {
StringBuilder currentPosition = new StringBuilder();
currentPosition.append("纬度:").append(bdLocation.getLatitude()).append("\n");
currentPosition.append("经度:").append(bdLocation.getLongitude()).append("\n");
currentPosition.append(bdLocation.getCountry()).append("\t");
currentPosition.append(bdLocation.getProvince()).append("\t");
currentPosition.append(bdLocation.getCity()).append("\t");
currentPosition.append(bdLocation.getDistrict()).append("\t");
currentPosition.append(bdLocation.getStreet()).append("\n");
currentPosition.append("定位方式:");
if(bdLocation.getLocType() == BDLocation.TypeGpsLocation) {
currentPosition.append("GPS");
}else if(bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
currentPosition.append("NetWork");
}
navigateTo(bdLocation);
positionText.setText(currentPosition);
}
}
显示地图
//添加显示地图的控件
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true">
</com.baidu.mapapi.map.MapView>
//初始化
SDKInitializer.initialize(getApplicationContext());
mapView = (MapView) findViewById(R.id.bmapView);
//管理其生命周期
@Override
protected void onPostResume() {
super.onPostResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
显示当前定位到的位置并且显示小光标标记
//初始化
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 locationBuilder = new MyLocationData.Builder();
locationBuilder.latitude(location.getLatitude());
locationBuilder.longitude(location.getLongitude());
MyLocationData locationData = locationBuilder.build();
baiduMap.setMyLocationData(locationData);
Log.d("TAG", "navigateTo: ");
}