I have a Android App that I am building that uses Google Maps and when I try to get the current location the map is zooming in and out

StackOverflow https://stackoverflow.com/questions/15532481

Question

Below is the Location Listener I am using and the method that calls it. When I run this the map is continuously zooming in and out. I am currently calling this from the onCreate in my activity. What is it I am doing wrong here?

private void showCurrentLocationOnMap(){
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    LocationListener ll = new Mylocationlistener();
    boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (!isGPS){
        Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
        intent.putExtra("enabled", true);
        sendBroadcast(intent);
    }

    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);




}


/**
 *Mylocationlistener class will give the current GPS location 
 *with the help of Location Listener interface 
 */
private class Mylocationlistener implements LocationListener {

    @Override
    public void onLocationChanged(Location location) {

        if (location != null) {
            // ---Get current location latitude, longitude, altitude & speed ---

            Log.d("LOCATION CHANGED", location.getLatitude() + "");
            Log.d("LOCATION CHANGED", location.getLongitude() + "");
            currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
            HAMBURG = new LatLng(location.getLatitude(), location.getLongitude());
            //This only shows the initial marker
                  @SuppressWarnings("unused")
      Marker hamburg = map.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
            // Move the camera instantly to hamburg with a zoom of 15.
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
            // Zoom in, animating the camera.
            map.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);              


        }
    }
Was it helpful?

Solution

I found that every 0 seconds I was asking for a location update as per the requestLocationUpdates method, just a typo on my part. As always it was something small that was killing me. So instead of :

 lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);

I should have had:

 lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, ll);

with the 10000 being equivalent to ten seconds. Once I changed this I was able to successfully run the app just fine with the updates updating correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top