简体   繁体   中英

Google Maps Camera reset the current position after a second

I am using google map api to show user current location and surrounding some mentioned area by below code.

@Override
public void onLocationChanged(Location location) {

   double latitude = location.getLatitude();
   double longitude = location.getLongitude();

   LatLng latLng = new LatLng(latitude,longitude);

   mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f));
   mMap.getUiSettings().setZoomControlsEnabled(true);
   mMap.setMyLocationEnabled(true);

    //call mentioned area to display
   getLocation();
}

But thing is that when I change the location by dragging OR zoomIn/zoomOut it immediately reset in previous position.

I want to move anywhere by dragging and control zoomIn,zoomOut also as my wish. Just when I click on MyLocation button then should go to my current position.

Note: When I off below code then it takes some few seconds to reset

//mMap.getUiSettings().setZoomControlsEnabled(true);
//mMap.setMyLocationEnabled(true);

Thanks in advance.

You wrote code to move Camera in onLocationChanged override method, so that on some time interval its getting change in location latitude and longitude(may be minor changes).

To avoid this remove this code

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f));
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setMyLocationEnabled(true);

from onLocationChanged method and write it in a outside method and call it when its necessary(like on the click of button)

However, Solve this issue by defining a boolean flag

private boolean flag = true;

and then check it before moving the camera

@Override
public void onLocationChanged(Location location) {

   double latitude = location.getLatitude();
   double longitude = location.getLongitude();

   LatLng latLng = new LatLng(latitude,longitude);

   if (flag) {
        flag = false;
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f));
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.setMyLocationEnabled(true);
    }

    //call mentioned area to display
   getLocation();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM