entre Desarrolladores

Recibe ayuda de expertos

Registrate y pregunta

Es gratis y fácil

Recibe respuestas

Respuestas, votos y comentarios

Vota y selecciona respuestas

Recibe puntos, vota y da la solución

Pregunta

3votos

problema con Geolocalizacion en Android Studio

Hola,
Estoy realizando una aplicación en Android Studio que muestra varios lugares (marcadores) en un Mapa y deseo que cuando se abra la aplicación muestre la ubicación en tiempo real del usuario (quien abre la aplicación) y que lugares están mas cercanos a el.
Que cuando muestre la ubicación del usuario haga una acercamiento en el mapa.

Este es el código que tengo en Java

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MiamiActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate ( Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_miami );
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById( R.id.map );
        mapFragment.getMapAsync( this );

    }

    @Override
    public void onMapReady ( GoogleMap googleMap ) {
        mMap = googleMap;
        mMap.setMapType( GoogleMap.MAP_TYPE_NORMAL );
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setZoomGesturesEnabled(true);
        mMap.getUiSettings().setCompassEnabled(true);

        // Subway (2962 SW 8th)
        LatLng subway2962 = new LatLng( 25.764590, -80.242120 );
        mMap.addMarker( new MarkerOptions().position( subway2962 ).title( "Subway" ).icon( BitmapDescriptorFactory.defaultMarker( BitmapDescriptorFactory.HUE_VIOLET ) ) );
        mMap.moveCamera( CameraUpdateFactory.newLatLng( subway2962 ) );

        // Moe’s Southwest Grill (Jackson Memorial)
        LatLng Moes_Southwest_Grill = new LatLng( 25.792320, -80.210830 );
        mMap.addMarker( new MarkerOptions().position( Moes_Southwest_Grill ).title( "Moe’s Southwest Grill" ).icon( BitmapDescriptorFactory.defaultMarker( BitmapDescriptorFactory.HUE_VIOLET ) ) );
        mMap.moveCamera( CameraUpdateFactory.newLatLng( Moes_Southwest_Grill ) );

        // The Smoothie Shop (Brickell)
        LatLng The_Smoothie_Shop = new LatLng( 25.762160, -80.189110 );
        mMap.addMarker( new MarkerOptions().position( The_Smoothie_Shop ).title( "The Smoothie Shop" ).icon( BitmapDescriptorFactory.defaultMarker( BitmapDescriptorFactory.HUE_VIOLET ) ) );
        mMap.moveCamera( CameraUpdateFactory.newLatLng( The_Smoothie_Shop ) );

    }

}

Gracias.

1 Respuesta

3votos

manichov1972 Puntos310

Ya lo logre, ya logre poner la posición actual en el mapa junto con los lugares (marker).

Este es el Código ya funcionando.

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
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 com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;

public class MiamiActivity extends AppCompatActivity implements OnMapReadyCallback {

    @Override
    public void onMapReady ( GoogleMap googleMap ) {
        Toast.makeText( this, "Map is Ready", Toast.LENGTH_SHORT ).show();
        Log.d( TAG, "onMapReady: map is ready" );
        mMap = googleMap;

        // Subway (2962 SW 8th)
        LatLng subway2962 = new LatLng(25.764590, -80.242120);
        mMap.setMapType( GoogleMap.MAP_TYPE_NORMAL );
        mMap.addMarker(new MarkerOptions().position(subway2962).title("Subway"));

        // Moe’s Southwest Grill (Jackson Memorial)
        LatLng Moes_Southwest_Grill = new LatLng( 25.792320, -80.210830 );
        mMap.addMarker( new MarkerOptions().position( Moes_Southwest_Grill ).title( "Moe’s Southwest Grill" ).icon( BitmapDescriptorFactory.defaultMarker( BitmapDescriptorFactory.HUE_VIOLET ) ) );
        mMap.moveCamera( CameraUpdateFactory.newLatLng( Moes_Southwest_Grill ) );

        // The Smoothie Shop (Brickell)
        LatLng The_Smoothie_Shop = new LatLng( 25.762160, -80.189110 );
        mMap.addMarker( new MarkerOptions().position( The_Smoothie_Shop ).title( "The Smoothie Shop" ).icon( BitmapDescriptorFactory.defaultMarker( BitmapDescriptorFactory.HUE_VIOLET ) ) );
        mMap.moveCamera( CameraUpdateFactory.newLatLng( The_Smoothie_Shop ) );

        if (mLocationPermissionsGranted) {
            getDeviceLocation();

            if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mMap.setMyLocationEnabled( true );

        }
    }

    private static final String TAG = "MapActivity";

    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final float DEFAULT_ZOOM = 15f;

    //vars
    private Boolean mLocationPermissionsGranted = false;
    private GoogleMap mMap;
    private FusedLocationProviderClient mFusedLocationProviderClient;

    @Override
    protected void onCreate ( @Nullable Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_miami );

        getLocationPermission();
    }

    private void getDeviceLocation () {
        Log.d( TAG, "getDeviceLocation: getting the devices current location" );

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient( this );

        try {
            if (mLocationPermissionsGranted) {

                final Task location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener( new OnCompleteListener() {
                    @Override
                    public void onComplete ( @NonNull Task task ) {
                        if (task.isSuccessful()) {
                            Log.d( TAG, "onComplete: found location!" );
                            Location currentLocation = (Location) task.getResult();

                            moveCamera( new LatLng( currentLocation.getLatitude(), currentLocation.getLongitude() ), DEFAULT_ZOOM );

                        } else {
                            Log.d( TAG, "onComplete: current location is null" );
                            Toast.makeText( MiamiActivity.this, "unable to get current location", Toast.LENGTH_SHORT ).show();
                        }
                    }
                } );
            }
        } catch (SecurityException e) {
            Log.e( TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
        }
    }

    private void moveCamera ( LatLng latLng, float zoom ) {
        Log.d( TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLng)      // Sets the center of the map to User Location View
                .zoom(15)                   // Sets the zoom
                .bearing(90)                // Sets the orientation of the camera to east
                .tilt(30)                   // Sets the tilt of the camera to 30 degrees
                .build();                   // Creates a CameraPosition from the builder
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        mMap.getUiSettings().setMyLocationButtonEnabled(true );
    }

    private void initMap () {
        Log.d( TAG, "initMap: initializing map" );
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById( R.id.map );

        mapFragment.getMapAsync( MiamiActivity.this );
    }

    private void getLocationPermission () {
        Log.d( TAG, "getLocationPermission: getting location permissions" );
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};

        if (ContextCompat.checkSelfPermission( this.getApplicationContext(), FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission( this.getApplicationContext(), COURSE_LOCATION ) == PackageManager.PERMISSION_GRANTED) {
                mLocationPermissionsGranted = true;
                initMap();
            } else {
                ActivityCompat.requestPermissions( this, permissions, LOCATION_PERMISSION_REQUEST_CODE );
            }
        } else {
            ActivityCompat.requestPermissions( this, permissions, LOCATION_PERMISSION_REQUEST_CODE );
        }
    }

    @Override
    public void onRequestPermissionsResult ( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults ) {
        Log.d( TAG, "onRequestPermissionsResult: called." );
        mLocationPermissionsGranted = false;

        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            mLocationPermissionsGranted = false;
                            Log.d( TAG, "onRequestPermissionsResult: permission failed" );
                            return;
                        }
                    }
                    Log.d( TAG, "onRequestPermissionsResult: permission granted" );
                    mLocationPermissionsGranted = true;
                    //initialize our map
                    initMap();
                }
            }
        }
    }

}

0voto

Peter comentado

Gracias por compartir la solución, por favor selecciona la respuesta como correcta.

Por favor, accede o regístrate para responder a esta pregunta.

Otras Preguntas y Respuestas


...

Bienvenido a entre Desarrolladores, donde puedes realizar preguntas y recibir respuestas de otros miembros de la comunidad.

Conecta