出于某种原因(我不知道),将地图初始化从 onCreate() 移动到 onLocationChange() 的第一次调用就可以了。现在我的 onCreate() 很简单
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.map_activity);
}
我的 onStart() 是:
@Override
protected void onStart()
{
super.onStart();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(
LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(UPDATE_INTERVAL);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
}
@Override
public void onConnected(Bundle arg0)
{
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
我的 onLocationChange() 是
@Override
public void onLocationChanged(Location loc)
{
if (mMap == null)
{
mapFragment = SupportMapFragment.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.add(R.id.mapcontainer, mapFragment);
fragmentTransaction.commit();
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.getUiSettings().setAllGesturesEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.setMyLocationEnabled(false);
LatLng location = new LatLng(loc.getLatitude(), loc.getLongitude());
CameraPosition pos = new CameraPosition.Builder().target(location).zoom(12).build();
CameraUpdate cu = CameraUpdateFactory.newCameraPosition(pos);
mMap.animateCamera(cu);
if (mLocationClient.isConnected())
mLocationClient.removeLocationUpdates(this);
mLocationClient.disconnect();
Log.e(getClass().getSimpleName(), "lat = " + location.latitude + " long = " + location.longitude);
}
}
它有效,但现在我有一个不同的问题(地图似乎忽略了触摸事件)。我将为此创建一个单独的问题。