代码如下,注释都在里面了。
public class MapFragment extends SupportMapFragment {
private boolean isFirstLoc = true;
private LocationClient mLocClient;
/**
* 定位SDK监听函数
*/
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
// map view 销毁后不在处理新接收的位置
if (location == null) {
return;
}
updateLocation(location);
if (isFirstLoc) {
isFirstLoc = false;
}
}
public void onReceivePoi(BDLocation poiLocation) {
}
}
public MapFragment() {
super();
}
public static MapFragment newInstances() {
MapFragment fragment = new MapFragment();
return fragment;
}
@Override
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
// 定位初始化
mLocClient = new LocationClient(getActivity());
mLocClient.registerLocationListener(new MyLocationListenner());
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 打开gps
option.setScanSpan(0);
option.setCoorType("bd09ll"); // 设置坐标类型
getBaiduMap().setMapType(BaiduMap.MAP_TYPE_NORMAL);
// MapStatusUpdateFactory.zoomTo(20) 就是设置缩放等级的,
// 有时候定位成功了,在当前的位置要显示自己的的位置,如果你的缩放等级不够的话
// 显示的范围会很大,用户体验不够好。
// 最后面是设置20的时候的页面,基本上满足需求了。
getBaiduMap().setMapStatus(MapStatusUpdateFactory.zoomTo(20));
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
.fromResource(R.drawable.icon_geo);
getBaiduMap().setMyLocationEnabled(true);
getBaiduMap().setMyLocationConfigeration(new MyLocationConfiguration(
MyLocationConfiguration.LocationMode.NORMAL, true, bitmapDescriptor));
mLocClient.setLocOption(option);
mLocClient.start();
mLocClient.requestLocation();
}
@Override
public void onPause() {
super.onPause();
getMapView().onPause();
}
@Override
public void onResume() {
super.onResume();
getMapView().onResume();
}
@Override
public void onStop() {
super.onStop();
mLocClient.stop();
}
// 更新地图上的位置
private void updateLocation(BDLocation bdLocation) {
MyLocationData locData = new MyLocationData.Builder()
.accuracy(bdLocation.getRadius())
.direction(100).latitude(bdLocation.getLatitude())
.longitude(bdLocation.getLongitude()).build();
getBaiduMap().setMyLocationData(locData);
LatLng ll = new LatLng(bdLocation.getLatitude(),
bdLocation.getLongitude());
MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
getBaiduMap().animateMapStatus(u);
}
}
大小这个级别就可以满足需求了