como obtener la nuestra posicion automatica en google map con android

Hola [email protected] hoy veremos un tutorial interesante ya hemos trabajado antes de como obtener las coordenadas del google map, pero esta ves veremos como cargar la dirección ni bien abrimos al google map en android.
como obtener la nuestra posición automática en google map con android studio
ESTRUCTURA
Creamos un nuevo proyecto, tendremos nuestro MainActivy y debemos crear otra actividad llamada MapsActivity, como se muestra en la siguiente imagen.
Paso 1:
Debemos ir a nuestro AndroManifest y agregar  los siguientes permisos y nuestra api key.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androfast.pc.appobtenermiubicacionmap">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<application
android
:allowBackup="true"
android
:icon="@mipmap/ic_launcher"
android
:label="@string/app_name"
android
:supportsRtl="true"
android
:theme="@style/AppTheme">

<meta-data
android
:name="com.google.android.geo.API_KEY"
android
:value="Tu Api key" />

<activity
android
:name=".MainActivity"
android
:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android
:name=".MapsActivity"
android
:label="@string/app_name">
</activity>


</application>

</manifest>
Paso 2:
Ir al build.gradle y agregar lo siguiente para poder usar los servicios de google.

    compile 'com.google.android.gms:play-services:9.8.0'
Paso 3:
En nuestro MainActivity debe tener lo siguiente:

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private final int REQUEST_PERMISSION = 10;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Log.d("MainActivity", "onCreate()");

if(Build.VERSION.SDK_INT >= 23){
checkPermission();
}
else{
locationActivity();
}
}

//Confirmar permiso de información de la ubicación
public void checkPermission() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
locationActivity();
}
// En caso de negarse
else{
requestLocationPermission();
}
}

//Pedir permiso
private void requestLocationPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION);

} else {
Toast toast = Toast.makeText(this, "La aplicación no puede ejecutarse a menos que esté permitida", Toast.LENGTH_SHORT);
toast.show();

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, REQUEST_PERMISSION);

}
}

//Recibir resultados
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_PERMISSION) {
// Permitido para usar
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationActivity();
return;

} else {
// Sin embargo, la respuesta en el momento de la denegación
Toast toast = Toast.makeText(this, "Fin de la aplicacion", Toast.LENGTH_SHORT);
toast.show();
}
}
}

// Ubicación en el Intent
private void locationActivity() {
Intent intent = new Intent(getApplication(), MapsActivity.class);
startActivity(intent);
}
}

Nuestro MapsActivity debe contener lo siguiente:

import android.support.v4.app.ActivityCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;


public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener, GoogleMap.OnMyLocationButtonClickListener, LocationSource {

private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationRequest locationRequest;

private OnLocationChangedListener onLocationChangedListener = null;

private int priority[] = {LocationRequest.PRIORITY_HIGH_ACCURACY, LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY,
LocationRequest.PRIORITY_LOW_POWER, LocationRequest.PRIORITY_NO_POWER};
private int locationPriority;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

// LocationRequest Para generar precisión e intervalo
locationRequest = LocationRequest.create();

// Precisión del posicionamiento, prioridad del consumo de energía
locationPriority = priority[1];

if(locationPriority == priority[0]){
// Al dar prioridad a la precisión de la información de posición
locationRequest.setPriority(locationPriority);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(16);
}
else if(locationPriority == priority[1]){
// Consideración del consumo de energía
locationRequest.setPriority(locationPriority);
locationRequest.setInterval(60000);
locationRequest.setFastestInterval(16);
}
else if(locationPriority == priority[2]){
locationRequest.setPriority(locationPriority);
}
else{
// Solo posicionamiento con disparador externo
locationRequest.setPriority(locationPriority);
}

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}

// onResume Conéctese al ingresar
@Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}

// onPauseCortar
@Override
public void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
}

@Override
public void onMapReady(GoogleMap googleMap) {

// check permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Log.d("debug", "permiso concedido");

mMap = googleMap;
// default de LocationSource Cambiar de fuente a fuente propia
mMap.setLocationSource(this);
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
}
else{
Log.d("debug", "error de permiso");
return;
}
}

@Override
public void onLocationChanged(Location location) {
Log.d("debug","onLocationChanged");
if (onLocationChangedListener != null) {
onLocationChangedListener.onLocationChanged(location);

double lat = location.getLatitude();
double lng = location.getLongitude();

Log.d("debug","location="+lat+","+lng);

Toast.makeText(this, "location="+lat+","+lng, Toast.LENGTH_SHORT).show();

// Add a marker and move the camera
LatLng newLocation = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(newLocation).title("Mi ubicacion"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(newLocation));

}
}

@Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Log.d("debug", "permiso concedido");

LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, locationRequest, this);
}
else{
Log.d("debug", "error de permiso");
return;
}
}

@Override
public void onConnectionSuspended(int i) {
Log.d("debug", "onConnectionSuspended");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("debug", "onConnectionFailed");
}

@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "onMyLocationButtonClick", Toast.LENGTH_SHORT).show();

return false;
}

@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
this.onLocationChangedListener = onLocationChangedListener;
}

@Override
public void deactivate() {
this.onLocationChangedListener = null;
}
}

Paso 4:
Nuestro archivo xml activity_maps

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">

<fragment
android:id="@+id/map"
android:layout_width="374dp"
android:layout_height="495dp"
android:layout_alignParentTop="true"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_weight="0.97" />
</LinearLayout>

Con eso hemos culminado, ni bien cargue la aplicación te mostrara tu posición de forma automática en el google map.

0

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *