TesterABC
TesterABC

Reputation: 1226

Cannot Zoom Android Map fragment to the current location

This is not the first question im posting regarding this matter in Stack Overflow. I really need help to zoom my map fragment to the current location. Please don't think I'm not trying anything. I tried a lot.

I need to zoom my map to the current location and no matter how hard I tried map zoom to another location not my current location. Cannot even possibly think what is happening here.

Here is my GoogleMapsFragment.java

public class GoogleMapsFragment extends android.support.v4.app.Fragment implements LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    View rootView;
    private GoogleApiClient mGoogleApiClient;
    private GoogleMap map;
    private LatLng latlng;

    public GoogleMapsFragment()
    {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if(!isGooglePlayServiceAvailable())
        {
           return null;
        }

        if(rootView != null)
        {
            ViewGroup parent = (ViewGroup)rootView.getParent();
            if(parent != null)
            {
                parent.removeView(rootView);
            }
        }
        else
        {
            rootView = inflater.inflate(R.layout.google_maps, container, false);
            map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
                    .getMap();

            SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                    .findFragmentById(R.id.map);

            if (mapFragment != null)
                mapFragment.getMapAsync(this);

            if (mGoogleApiClient == null) {
                mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                        .addApi(LocationServices.API).addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this).build();
                mGoogleApiClient.connect();
            }
        }

        return rootView;
    }

    @Override
    public void onLocationChanged(Location location) {

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

        LatLng latLng = new LatLng(latitude, longitude);

        map.addMarker(new MarkerOptions().position(latLng));
        map.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        map.animateCamera(CameraUpdateFactory.zoomTo(15));
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    private boolean isGooglePlayServiceAvailable()
    {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if(ConnectionResult.SUCCESS == status)
        {
            return true;
        }
        else
        {
            GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
            return false;
        }
    }

    //Zoom to the current location
    public Location getMyLocation() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        if (location != null)
        {
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location.getLongitude()), 13));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
                    .zoom(17)                   // Sets the zoom
                    .bearing(90)                // Sets the orientation of the camera to east
                    .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                    .build();                   // Creates a CameraPosition from the builder
            map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }

        return location;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;

        // Zoom in, animating the camera.
        map.animateCamera(CameraUpdateFactory.zoomTo(5), 5000, null);
        map.getUiSettings().setZoomControlsEnabled(false);
        map.getUiSettings().setCompassEnabled(false);
        map.getUiSettings().setMyLocationButtonEnabled(true);
    }

    @Override
    public void onConnected(Bundle bundle) {

        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }
}

I think I've dome a small mistake and it zooms to another location and it is not even close to my country.

Here is the image of my zooming location.

Screen Shot of the Map

Someone please tell me how to zoom my map fragment to the current location.

Any kind of help may appreciated. :)

~ Edit for Gaurav ~

Added getMyLocation() inside onMapReady()

    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;

        getMyLocation();

        // Zoom in, animating the camera.
        map.animateCamera(CameraUpdateFactory.zoomTo(5), 5000, null);
        map.getUiSettings().setZoomControlsEnabled(false);
        map.getUiSettings().setCompassEnabled(false);
        map.getUiSettings().setMyLocationButtonEnabled(true);


    }

~ Edited full code ~

public class GoogleMapsFragment extends android.support.v4.app.Fragment implements LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    View rootView;
    private GoogleApiClient mGoogleApiClient;
    private GoogleMap map;
    private LatLng latlng;

    public GoogleMapsFragment()
    {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if(!isGooglePlayServiceAvailable())
        {
           return null;
        }

        if(rootView != null)
        {
            ViewGroup parent = (ViewGroup)rootView.getParent();
            if(parent != null)
            {
                parent.removeView(rootView);
            }
        }
        else
        {
            rootView = inflater.inflate(R.layout.google_maps, container, false);
            map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
                    .getMap();

            SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                    .findFragmentById(R.id.map);

            if (mapFragment != null)
                mapFragment.getMapAsync(this);

            if (mGoogleApiClient == null) {
                mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                        .addApi(LocationServices.API).addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this).build();
                mGoogleApiClient.connect();
            }
        }

        return rootView;
    }

    @Override
    public void onLocationChanged(Location location) {

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

        LatLng latLng = new LatLng(latitude, longitude);

        map.addMarker(new MarkerOptions().position(latLng));
        map.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        map.animateCamera(CameraUpdateFactory.zoomTo(15));
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    private boolean isGooglePlayServiceAvailable()
    {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if(ConnectionResult.SUCCESS == status)
        {
            return true;
        }
        else
        {
            GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
            return false;
        }
    }

    //Zoom to the current location
    public Location getMyLocation() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        if (location != null)
        {
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location.getLongitude()), 13));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
                    .zoom(17)                   // Sets the zoom
                    .bearing(90)                // Sets the orientation of the camera to east
                    .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                    .build();                   // Creates a CameraPosition from the builder
            map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }

        return location;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;

        Location myLocation =  getMyLocation();

        LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                latLng
                , 15));

    }

    private LocationRequest mLocationRequest;
    private static final long INTERVAL = 1000 * 1000;
    private static final long FASTEST_INTERVAL = 1000 * 900;

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);

    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }
}

~ Error Log ~

06-16 11:23:28.180    6647-6647/com.myayubo E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.myayubo, PID: 6647
    java.lang.NullPointerException
            at com.myayubo.GoogleMapsFragment.onMapReady(GoogleMapsFragment.java:151)
            at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
            at com.google.android.gms.maps.internal.zzl$zza.onTransact(Unknown Source)
            at android.os.Binder.transact(Binder.java:361)
            at com.google.android.gms.maps.internal.v$a$a.a(:com.google.android.gms.alldynamite:82)
            at maps.ei.bu$6.run(Unknown Source)
            at android.os.Handler.handleCallback(Handler.java:808)
            at android.os.Handler.dispatchMessage(Handler.java:103)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
            at dalvik.system.NativeStart.main(Native Method)

Upvotes: 2

Views: 2211

Answers (3)

Vishal Thareja
Vishal Thareja

Reputation: 128

Firstly check whether you are receiving location coordinates values or not, if receiving try using this one

 googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

This could be useful for you.

Upvotes: 0

Gaurav
Gaurav

Reputation: 3763

Here it is:

 @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;

       Location myLocation =  getMyLocation();

LatLng latLng = new LatLng(myLocation.getlatitude(), myLocation.getLongitude());
 map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                latLng
                , 15));
}

and

private LocationRequest mLocationRequest;
    private static final long INTERVAL = 1000 * 1000;
    private static final long FASTEST_INTERVAL = 1000 * 900;
 @Override
    public void onConnected(Bundle bundle) {

       mLocationRequest = new LocationRequest();
                mLocationRequest.setInterval(INTERVAL);
                mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
                mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    }

this will call onLocationChanged();

Upvotes: 2

ashishdhiman2007
ashishdhiman2007

Reputation: 817

Try calling onLocationChanged(), from within getMyLocation()

Upvotes: 0

Related Questions