Codigo completo:
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback {
private static final String[] PERMISOS = {
Manifest.permission.ACCESS_FINE_LOCATION
};
private static int REQUEST_CODE = 1;
private GoogleApiClient googleApiClient;
private Location ultimaUbicacion;
Double latitudObtenida;
Double longitudObtenida;
private TextView txtLat;
private TextView txtLon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView)findViewById(R.id.txtLat);
txtLon = (TextView)findViewById(R.id.txtLon);
if (googleApiClient == null){
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
int leer = ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION);
if (leer == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, PERMISOS, REQUEST_CODE);
}
final LatLng BUENOS_AIRES = new LatLng(-34.637936, -58.406372);
googleMap.addMarker(new MarkerOptions()
.position(BUENOS_AIRES)
.title("Prueba")
.snippet("Población: 2,965 millones")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
// .alpha(.5f)
// .flat(true)
.draggable(true));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitudObtenida, longitudObtenida), 2.0f));
}
@Override
public void onConnected(@Nullable Bundle bundle) {
int leer = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
if (leer == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, PERMISOS, REQUEST_CODE);
}
ultimaUbicacion = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (ultimaUbicacion != null){
latitudObtenida = ultimaUbicacion.getLatitude();
longitudObtenida = ultimaUbicacion.getLongitude();
}
}
@Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
@Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}