Search code examples
androidgoogle-mapsgesture

control user gesture on my map


I new in coding google map, my question is how i control the user gestur drag , zoom in and zoom out. because my code always back to the current location of user when i zoomin/out, nad when i drag/ scroll up, down, left, right. always back to the current possition .

its my code for current loc user

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {
            LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
            mMarker = mMap.addMarker(new MarkerOptions().position(loc));
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
        }
    };

Solution

  • You can use a boolean to move the camera only the first time:

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener {
        private GoogleMap mMap;
        private Marker mMarker;
        private boolean firstTime = true;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);
    
            ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map)).getMapAsync(this);
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            mMap.setMyLocationEnabled(true);
            mMap.setOnMyLocationChangeListener(this);
        }
    
        @Override
        public void onMyLocationChange(Location location) {
            LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
            mMarker = mMap.addMarker(new MarkerOptions().position(loc));
    
            if (firstTime) {
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
                firstTime = false;
            }
        }
    }
    

    NOTE: Take into account that this example uses GoogleMap.OnMyLocationChangeListener only because that is the method that you are using in your question, but it's deprecated and you must use the FusedLocationProviderApi according to the documentation:

    public final void setOnMyLocationChangeListener (GoogleMap.OnMyLocationChangeListener listener)

    This method was deprecated. use com.google.android.gms.location.FusedLocationProviderApi instead. FusedLocationProviderApi provides improved location finding and power usage and is used by the "My Location" blue dot. See the MyLocationDemoActivity in the sample applications folder for example example code, or the Location Developer Guide.