Google Maps Android API V2具有LocationSource。根据文档:
“GoogleMap对象具有内置的位置提供程序,用于其我的位置图层,但可以用实现此接口的另一个位置提供程序替换它。”
您需要与LocationSource.OnLocationChangedListener一起使用它。
更新
弄清楚了。如果您想要类似于runOnFirstFix的东西,则以下是等待用户位置可用的基本示例,然后将地图动画显示在其位置中心。
public class MyLocationMapFragmentActivity extends FragmentActivity implements LocationListener, LocationSource
{
private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_map);
this.mContext = this;
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestLocationUpdates(locationManager.getBestProvider(locationCriteria, true), 1L, 2F, this);
setUpMapIfNeeded();
}
@Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
super.onPause();
}
@Override
public void onResume()
{
super.onResume();
setUpMapIfNeeded();
if(locationManager != null)
{
mMap.setMyLocationEnabled(true);
}
}
private void setUpMapIfNeeded() {
if (mMap == null)
{
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.basicMap)).getMap();
mMap.setLocationSource(this);
if (mMap != null)
{
setUpMap();
}
}
}
private void setUpMap()
{
mMap.setMyLocationEnabled(true);
}
@Override
public void activate(OnLocationChangedListener listener)
{
mListener = listener;
}
@Override
public void deactivate()
{
mListener = null;
}
@Override
public void onLocationChanged(Location location)
{
if( mListener != null )
{
mListener.onLocationChanged( location );
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
}
}
@Override
public void onProviderDisabled(String provider)
{
Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider)
{
Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}
}
更新2:
如果您希望在用户的位置超出屏幕时将地图居中显示在该位置(就像旧API中的MyLocationOverlay一样),请参见
this answer或这篇博客文章:
Google Maps Android API V2 MyLocation LocationSource and event handling。