代碼如下,註釋都在裏面了。
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);
}
}
大小這個級別就可以滿足需求了