【问题标题】:Google Map api v2 Marker not moving until I rotate the phone and the map "refreshes"Google Map api v2 Marker 在我旋转手机并且地图“刷新”之前不会移动
【发布时间】:2015-02-20 23:49:06
【问题描述】:

我有以下代码:

公共类 MapsActivity 扩展 FragmentActivity 实现 GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, 位置监听器 {

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);
    }
}

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

【问题讨论】:

    标签: java android google-maps location marker


    【解决方案1】:

    当标记被复制时,你看到的实际上是系统在工作:

    1. 第一次获得位置时,会添加一个标记,太棒了。
    2. 如果有新职位出现,请致电handleNewLocation(location),然后添加一个新标记:mMap.addMarker(camion);

    为避免这种情况,请始终使用相同的标记并在必要时更新其位置:

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

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

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

    【讨论】:

    • 非常感谢何塞!但是断开连接和清理是什么意思?你的意思是重写 onResume 或 onStop 中的代码?
    • 不!是的,目前您的 onStop 中的代码是不必要的,因为该过程将首先访问 onPause 并负责断开 Google 客户端的连接。
    • 何塞,我知道这可能会惹恼你,但我需要完成这个项目,我不知道如何解决这个错误,你能通过电子邮件帮助我吗?
    • 在 G+ 中找到我不会很困难。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多