谷歌地图api v2标记不动,直到我旋转手机和地图“刷新”

时间:2015-02-20 23:49:07

标签: java android google-maps location marker

我有以下代码:

公共类MapsActivity扩展了FragmentActivity实现         GoogleApiClient.ConnectionCallbacks,         GoogleApiClient.OnConnectionFailedListener,         LocationListener {

private GoogleMap mMap; // Might be null if Google Play services APK is not available.


// LogCat tag
private static final String TAG = MapsActivity.class.getSimpleName();

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

private Location mLastLocation;

// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;

// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;

private LocationRequest mLocationRequest;

// Location updates intervals in sec
private static int UPDATE_INTERVAL = 5000; // 10 sec
private static int FASTEST_INTERVAL = 1000; // 5 sec
private static int DISPLACEMENT = 5; // 10 meters

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } 
        return false;
    }
    return true;
}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();
}

protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();

    // First we need to check availability of play services
    if (checkPlayServices()) {

        // Building the GoogleApi client
        buildGoogleApiClient();

        createLocationRequest();
    }
}

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();
    if (mGoogleApiClient.isConnected()) {//eliminando updates y desconectando
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }

}

@Override
protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}




private void setUpMapIfNeeded() {
    // hacer una pruba de null para saber si mMap esta activo
    if (mMap == null) {
        // obtener el mapa por SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // verificar si el mapa esta activo
        if (mMap != null) {
            setUpMap();
        }
    }
}

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {
    }

@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG, "Servicios de localización activados");
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) { //Se llama cuando no hay una ultima localización disponible
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    else {
        handleNewLocation(location);
    }
}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "Servicios de localización suspendidos. Favor de reconectar.");
}

//Metodo para cuando la localización cambia
@Override
public void onLocationChanged(Location location) {
    handleNewLocation(location);
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

        Log.i(TAG, "Servicio de localización falló con el siguiente codigo: "+connectionResult.getErrorCode());
    }



private void handleNewLocation(Location location) {

    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);


        //añadir un nuevo marker con la posición de la variable latLng
        MarkerOptions camion = new MarkerOptions()
                .position(latLng)
                .title("Camión");
        mMap.addMarker(camion);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        CameraUpdate zoom=CameraUpdateFactory.zoomTo(19);
        mMap.animateCamera(zoom);
    }
}

我希望标记在手机移动时移动,但它不会移动,直到我旋转手机并且屏幕旋转然后地图刷新并且标记移动到我的实际位置,有时标记重复并且如果我旋转手机重复的标记消失。 知道为什么会这样吗?谢谢

1 个答案:

答案 0 :(得分:0)

标记重复时看到的内容实际上是系统正在运行:

  1. 第一次获得一个位置时,会添加一个标记,一切都很酷。
  2. 如果有新职位,请致电handleNewLocation(location)并添加新标记:mMap.addMarker(camion);
  3. 为避免这种情况,请始终使用相同的标记并在必要时更新其位置:

    if(mCamionMarker == null){ 
        mCamionMarker = mMap.addMarker(camion);
    }else{
        mCamionMarker.setPosition(latLng);
    }
    

    当您没有获得更新时,其他时间是因为api认为它无法为您提供更好的位置。

    考虑在onResume或onStop上断开连接和清理,但不要同时在两者上断开连接。