简体   繁体   中英

Not able to get current location latitude and longitude in android

I am new in android and i want to fetch my current location longitude and latitude and i have used this code to fetch my latitude and longitude and i cannot see the results in my logcat and i have also moved the google-services.json file app/ and intialised the mGoogleApiClient and mLastLocation and i am not getting any error then why i am not able to see the latitude and longitude.Please help me and thanks in advance here is the complete code of my app https://github.com/akashmalla07/GoogleMap please have a look if anyone can help me

Here is the code of Mapsactivity

    public class MapsActivity extends FragmentActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

         private GoogleMap mMap; 
         AppLocationService appLocationService;
         GoogleApiClient mGoogleApiClient;
         private Location mLastLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
                .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
                .addApi(LocationServices.API).build();

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);
       setUpMapIfNeeded();

    }

    private void setUpMapIfNeeded() {
        if (mMap == null) {
            mMap = ((SupportMapFragment) 
            getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            if (mMap != null) {
                displayLocation();
            }
        }
    }

    private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();

            Log.d("result", latitude + ", " + longitude);

        } else {

          Log.d("result3","(Couldn't get the location. Make sure location is 
          enabled on the device)");
        }
    }

    @Override
    public void onConnected(Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }
}

And these are the imports

  import android.location.Location;
  import android.os.Bundle;
  import android.support.v4.app.FragmentActivity;
  import android.util.Log;

  import com.google.android.gms.common.ConnectionResult; 
  import com.google.android.gms.common.api.GoogleApiClient;
  import com.google.android.gms.location.LocationListener;
  import com.google.android.gms.location.LocationServices;
  import com.google.android.gms.maps.GoogleMap;
  import com.google.android.gms.maps.SupportMapFragment;

Updated code-------------------------------------------

      public class MapsActivity extends Activity implements 
       GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener {

private static final String TAG = MapsActivity.class.getSimpleName();
private LocationRequest mLocationRequest;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private GoogleMap mMap;
AppLocationService appLocationService;
GoogleApiClient mGoogleApiClient;
private Location mLastLocation;

private TextView lblLocation;
private Button btnShowLocation, btnStartLocationUpdates;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    lblLocation = (TextView) findViewById(R.id.lblLocation);
    btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
    btnStartLocationUpdates = (Button) 
      findViewById(R.id.btnLocationUpdates);

    if (checkPlayServices()) {

        // Building the GoogleApi client
        buildGoogleApiClient();

      }

    btnShowLocation.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            displayLocation();
            Log.d("clicked","yes");
        }
    });

}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();
}
private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "This device is not supported.", Toast.LENGTH_LONG)
                    .show();
            finish();
        }
        return false;
    }
    return true;
}

@Override
protected void onStart() {
    super.onStart();
    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    }
}

@Override
protected void onResume() {
    super.onResume();

    checkPlayServices();

}

@Override
protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

@Override
protected void onPause() {
    super.onPause();

}
@Override
public void onConnectionFailed(ConnectionResult result) {
    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
            + result.getErrorCode());
}

@Override
public void onConnected(Bundle arg0) {

    displayLocation();


}



private void displayLocation() {
   Log.d("after","clicked");
    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();

        lblLocation.setText(latitude + ", " + longitude);
        Log.d("lat",String.valueOf(latitude));

    } else {
        Log.d("lat","No lat");

        lblLocation
                .setText("(Couldn't get the location. Make sure location is enabled on the device)");
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {

}

}

your forgot to call mGoogleApiClient.connect();

    public class MapsActivity extends FragmentActivity implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

     private GoogleMap mMap; 
     AppLocationService appLocationService;
     GoogleApiClient mGoogleApiClient;
     private Location mLastLocation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
            .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
            .addApi(LocationServices.API).build();

 mGoogleApiClient.connect();

}

private void setUpMapIfNeeded() {
    if (mMap == null) {
        mMap = ((SupportMapFragment) 
        getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        if (mMap != null) {
            displayLocation();
        }
    }
}

private void displayLocation() {

    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();

        Log.d("result", latitude + ", " + longitude);

    } else {

      Log.d("result3","(Couldn't get the location. Make sure location is 
      enabled on the device)");
    }
}

@Override
public void onConnected(Bundle bundle) {
          mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);
   setUpMapIfNeeded();
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}
} 

I have edited your code. See if this work.

There are 2 mistakes in your code

You are not connected to GoogleApiclient , so call mgoogleApiclient.connect just after you build it using builder.

Call your displayLocation() method in onConnected() callback method. As, this is the success callback of GoogleApiClient , which means you are now connected to the client and can get your location.

Also, You can get location without registering any GoogleApikey until you are not using Maps or Places Api in your app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM