Search code examples
androidandroid-maps-v2android-maps

onLocationChanged being called even when map is just moved


locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    centerOnMapLocation(location,"Your location");
                }

This method onLocationChanged should be called only when i set location from extented controls in emulator i.e. when the user's location is changed.

 public void centerOnMapLocation(Location location, String title){
        if(location!=null) {
            LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
            mMap.clear();
            mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 12));
        }
    }

centerOnMapLocation moves the camera to the location of the user. When i click set location from extented controls in emulator, the camera and marker is moved to the new location. That's fine. But after that, when i try to move the within the map, as soon as I stop touching the screen, the camera is moved back to the marker again.

Basically, when i slide within the map screen to move within the map, as soon as my slide stops(means i stop touching the screen), the camera is moved to the marker again. I want the marker to remain there and I should be able to move within the map as normal

Why is it happening when the camera should move only on location change and not map screen change


Solution

  • The following line provides location updates to the locationLister.

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
    

    The third parameter while asking for location updates is the minimum distance moved until location is updated. In the above case when 0 is passed, it updates the location continuously and locationLister takes it as a new location and cameraZoom is updated.

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,1,locationListener);
    

    To fix this, just change the value of minimum distance to some arbitrary value, here 1. Now until the location is changed, it won't call centerOnMapLocation.