estoy intentando crear un app de Google maps con un marcador que registre y muestre mi información mediante mi ubicación. El enunciado del ejercicio es el siguiente:
- En este ejercicio deberás crear una aplicación que en lugar de darle unas coordenadas, deberá coger esa situación de nuestra localización, deberás poner un marcador en ese punto con un snippet el cual deberá recoger la información de nuestra localización y mostrarla en ese snippet.
Mi código seria el siguiente:
-MainActivity.java
package com.example.kisko.ubicacionmaps;
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);
}
}
-MapsActivity.java
package com.example.kisko.ubicacionmaps;
import android.location.Address; import android.location.Geocoder; 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.Marker; import com.google.android.gms.maps.model.MarkerOptions;
import java.util.List; import java.util.Locale;
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 List<Address>direcciones;
private Geocoder geocoder;
private MarkerOptions marker;
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);
mMap = googleMap;
mMap.setMinZoomPreference(10);
mMap.setMaxZoomPreference(20);
geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
} 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);
Marker addMarker = mMap.addMarker(new MarkerOptions().position(newLocation).title("Hola"));
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, "¡Lugar donde estoy!", Toast.LENGTH_SHORT).show();
return false;
}
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
this.onLocationChangedListener = onLocationChangedListener;
}
@Override
public void deactivate() {
this.onLocationChangedListener = null;
}
}
-Activity_Maps.xml
<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" />
Yo pretendo insertar estos datos: String direccion = direcciones.get(0).getAddressLine(0); String ciudad = direcciones.get(0).getLocality(); String estado = direcciones.get(0).getAdminArea(); String pais = direcciones.get(0).getCountryName(); String codigoPostal = direcciones.get(0).getPostalCode();
marker.setSnippet(direccion);
marker.showInfoWindow();
para conseguir hacer el ejercicio, pero no me sale por mas que lo intento. Mi meta es conseguir lo que dice el enunciado que cito al principio de la consulta. Un saludo y gracias de antemano