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

1voto

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();
                }
            }
        }
    }

}

Hasta aqui.
Ahora surgió algo nuevo:
Teniendo la ubicación actual del usuario, muestra un punto azul que es el pre-determinado por google maps. Deseo que en vez de ese punto azul aparezca una imagen (icono), por ejemplo un auto (Ya tengo la imagen lista).
Revisando en google encontre como poner esa imagen pero para una ubicación especifica con coordenadas, pero no para la ubicación actual del usuario que la muestra el gps.
como adapto eso a mi código actual ya arriba puesto?

private static final LatLng MELBOURNE = new LatLng(-37.813, 144.962);
  private Marker melbourne = mMap.addMarker(new MarkerOptions()
                            .position(MELBOURNE)
                            .title("Melbourne")
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));

Aqui pone una imagen (icono) en MELBOURNE AUSTRALIA, Yo quiero que ponga ese icono pero en la locación actual del usuario.

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

Otras Preguntas y Respuestas


Actividad Reciente

...

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

Conecta