Search code examples
javaandroidgps

How can I get the current GPS location?


I know that this has been asked before but all the solutions available require me to use onLocationChanged() method so I can use the getLatitude() and getLongitude() methods to get coordinates.

But onLocationChanged() will be called when the location of my device is changed. So in order to get my current location I would have to move my device.

But I want to get the current coordinates without having to move my device. Also I read somewhere that I can call the onLocationChanged() method manually and I can get the last known location but again. Isn't it possible that the last known location won't be my current location? or is it ok to use the last known location solution?

This is part of a class that I am using to implement LocationListener.

public class MyLocListener extends MapsActivity implements LocationListener {

    public void onLocationChanged(Location location)
    {
        if(location!=null)
        {
            MapsActivity.setLatitude(location.getLatitude());
            MapsActivity.setLongitude(location.getLongitude());
        }
    }}

This is the override of the function I am using to provide coordinates to my map activity. latitude and longitude are two double type variables. In this class the latitude and longitude variables are initiated with 0 and they remain that way since the onLocationChanged() function is only called when my location is changed. Hence I can't see my current location on the map.

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


        LocationManager myLocManager;

        myLocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        MyLocListener loc = new MyLocListener();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        myLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loc);

        LatLng sydney = new LatLng(latitude, longitude);

        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

Solution

  • You Should use GooglePlayServices

    compile 'com.google.android.gms:play-services-location:7.0.0'
    

    To get location

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

    After connection

    public class MainActivity extends ActionBarActivity implements
            ConnectionCallbacks, OnConnectionFailedListener {
        ...
        @Override
        public void onConnected(Bundle connectionHint) {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);
            if (mLastLocation != null) {
                mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
                mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
            }
        }
    }
    

    For more detail information check documentation.