cómo obtener la ubicación actual en google map android

En realidad, mi problema es que no estoy actualizando la latitud y la longitud de la ubicación. Lo intenté de muchas maneras. Sé que esta pregunta ya me la hicieron. Así que probé las respuestas y aún así no recibí la respuesta. Por favor, ayúdenme Código:

if (googleMap == null) { googleMap = ((MapFragment) getFragmentManager().findFragmentById( R.id.map)).getMap(); // check if map is created successfully or not if (googleMap == null) { Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT) .show(); } } googleMap.setMyLocationEnabled(true); Location myLocation = googleMap.getMyLocation(); //Nullpointer exception......... LatLng myLatLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude()); CameraPosition myPosition = new CameraPosition.Builder() .target(myLatLng).zoom(17).bearing(90).tilt(30).build(); googleMap.animateCamera( CameraUpdateFactory.newCameraPosition(myPosition)); 

Por favor, compruebe el código de muestra para la API v3 Google Maps Android . Usar esto resolverá tu problema.

 private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); mMap.setMyLocationEnabled(true); // Check if we were successful in obtaining the map. if (mMap != null) { mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() { @Override public void onMyLocationChange(Location arg0) { // TODO Auto-generated method stub mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!")); } }); } } } 

Llame a esta función en la función onCreate .

Creo que la mejor manera ahora es:

 Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 

Documentación. Obteniendo la última ubicación conocida

 package com.example.sandeep.googlemapsample; import android.content.pm.PackageManager; import android.location.Location; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log; import android.view.View; 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.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.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMarkerDragListener, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerClickListener, View.OnClickListener { private static final String TAG = "MapsActivity"; private GoogleMap mMap; private double longitude; private double latitude; private GoogleApiClient googleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // 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); //Initializing googleApiClient googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); // googleMapOptions.mapType(googleMap.MAP_TYPE_HYBRID) // .compassEnabled(true); // Add a marker in Sydney and move the camera LatLng india = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(india).title("Marker in India")); mMap.moveCamera(CameraUpdateFactory.newLatLng(india)); mMap.setOnMarkerDragListener(this); mMap.setOnMapLongClickListener(this); } //Getting current location private void getCurrentLocation() { mMap.clear(); if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); if (location != null) { //Getting longitude and latitude longitude = location.getLongitude(); latitude = location.getLatitude(); //moving the map to location moveMap(); } } private void moveMap() { /** * Creating the latlng object to store lat, long coordinates * adding marker to map * move the camera with animation */ LatLng latLng = new LatLng(latitude, longitude); mMap.addMarker(new MarkerOptions() .position(latLng) .draggable(true) .title("Marker in India")); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(15)); mMap.getUiSettings().setZoomControlsEnabled(true); } @Override public void onClick(View view) { Log.v(TAG,"view click event"); } @Override public void onConnected(@Nullable Bundle bundle) { getCurrentLocation(); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onMapLongClick(LatLng latLng) { // mMap.clear(); mMap.addMarker(new MarkerOptions().position(latLng).draggable(true)); } @Override public void onMarkerDragStart(Marker marker) { Toast.makeText(MapsActivity.this, "onMarkerDragStart", Toast.LENGTH_SHORT).show(); } @Override public void onMarkerDrag(Marker marker) { Toast.makeText(MapsActivity.this, "onMarkerDrag", Toast.LENGTH_SHORT).show(); } @Override public void onMarkerDragEnd(Marker marker) { // getting the Co-ordinates latitude = marker.getPosition().latitude; longitude = marker.getPosition().longitude; //move to current position moveMap(); } @Override protected void onStart() { googleApiClient.connect(); super.onStart(); } @Override protected void onStop() { googleApiClient.disconnect(); super.onStop(); } @Override public boolean onMarkerClick(Marker marker) { Toast.makeText(MapsActivity.this, "onMarkerClick", Toast.LENGTH_SHORT).show(); return true; } } 
 public void getMyLocation() { // create class object gps = new GPSTracker(HomeActivity.this); // check if GPS enabled if (gps.canGetLocation()) { latitude = gps.getLatitude(); longitude = gps.getLongitude(); Geocoder geocoder; List
addresses; geocoder = new Geocoder(this, Locale.getDefault()); try { addresses = geocoder.getFromLocation(latitude, longitude, 1); postalCode = addresses.get(0).getPostalCode(); city = addresses.get(0).getLocality(); address = addresses.get(0).getAddressLine(0); state = addresses.get(0).getAdminArea(); country = addresses.get(0).getCountryName(); knownName = addresses.get(0).getFeatureName(); Log.e("Location",postalCode+" "+city+" "+address+" "+state+" "+knownName); } catch (IOException e) { e.printStackTrace(); } } else { gps.showSettingsAlert(); } }
 Location locaton; private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // 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; if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } mMap.setMyLocationEnabled(true); mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() { @Override public void onMyLocationChange(Location location) { CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())); CameraUpdate zoom = CameraUpdateFactory.zoomTo(11); mMap.clear(); MarkerOptions mp = new MarkerOptions(); mp.position(new LatLng(location.getLatitude(), location.getLongitude())); mp.title("my position"); mMap.addMarker(mp); mMap.moveCamera(center); mMap.animateCamera(zoom); } });}} 

Es posible que su ubicación actual no esté disponible inmediatamente después de inicializar el fragmento del mapa.

Después de establecer

 googleMap.setMyLocationEnabled(true); 

tienes que esperar hasta que veas el punto azul que se muestra en tu MapView. Entonces

 Location myLocation = googleMap.getMyLocation(); 

myLocation no será nulo.

Creo que es mejor que use el LocationClient en su lugar, e implemente su propio LocationListener.onLocationChanged (Location l)

Recibir actualizaciones de ubicación le mostrará cómo obtener la ubicación actual de LocationClient

Agregue los permisos al manifiesto de la aplicación

Agregue uno de los siguientes permisos como elemento secundario del elemento en su manifiesto de Android. O bien el permiso de ubicación aproximada:

  ...  ...  

O el permiso de ubicación correcta:

  ...  ...  

El siguiente ejemplo de código comprueba el permiso utilizando la biblioteca de soporte antes de habilitar la capa Mi ubicación:

 if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mMap.setMyLocationEnabled(true); } else { // Show rationale and request permission. } The following sample handles the result of the permission request by implementing the ActivityCompat.OnRequestPermissionsResultCallback from the Support library: @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == MY_LOCATION_REQUEST_CODE) { if (permissions.length == 1 && permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mMap.setMyLocationEnabled(true); } else { // Permission was denied. Display an error message. } } 

Este ejemplo proporciona una actualización de ubicación actual usando el proveedor de GPS. Todo el código de la aplicación de Android es el siguiente,

 import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.widget.TextView; import android.util.Log; public class MainActivity extends Activity implements LocationListener{ protected LocationManager locationManager; protected LocationListener locationListener; protected Context context; TextView txtLat; String lat; String provider; protected String latitude,longitude; protected boolean gps_enabled,network_enabled; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtLat = (TextView) findViewById(R.id.textview1); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } @Override public void onLocationChanged(Location location) { txtLat = (TextView) findViewById(R.id.textview1); txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude()); } @Override public void onProviderDisabled(String provider) { Log.d("Latitude","disable"); } @Override public void onProviderEnabled(String provider) { Log.d("Latitude","enable"); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.d("Latitude","status"); } } 

¿Por qué no usar FusedLocationApi lugar de OnMyLocationChangeListener ? Debe inicializar el objeto GoogleApiClient y utilizar el método LocationServices.FusedLocationApi.requestLocationUpdates() para registrar el detector de cambios de ubicación. Es importante tener en cuenta que no olvides eliminar el oyente registrado y desconectar GoogleApiClient .

 private LocationRequest mLocationRequest; private GoogleApiClient mGoogleApiClient; private LocationListener mLocationListener; private void initGoogleApiClient(Context context) { mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() { @Override public void onConnected(Bundle bundle) { mLocationRequest = LocationRequest.create(); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setInterval(1000); setLocationListener(); } @Override public void onConnectionSuspended(int i) { Log.i("LOG_TAG", "onConnectionSuspended"); } }).build(); if (mGoogleApiClient != null) mGoogleApiClient.connect(); } private void setLocationListener() { mLocationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { String lat = String.valueOf(location.getLatitude()); String lon = String.valueOf(location.getLongitude()); Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon); } }; LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener); } private void removeLocationListener() { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener); } 

Este código en MapsActivity Class funciona para mí:

 public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; LocationManager locationManager; LocationListener locationListener; public void centreMapOnLocation(Location location, String title){ LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude()); mMap.clear(); mMap.addMarker(new MarkerOptions().position(userLocation).title(title)); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,12)); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){ locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener); Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); centreMapOnLocation(lastKnownLocation,"Your Location"); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps2); // 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; Intent intent = getIntent(); if (intent.getIntExtra("Place Number",0) == 0 ){ // Zoom into users location locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { centreMapOnLocation(location,"Your Location"); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){ locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener); Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); centreMapOnLocation(lastKnownLocation,"Your Location"); } else { ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1); } } } } 
 public class MainActivity extends ActionBarActivity implements ConnectionCallbacks, OnConnectionFailedListener { ... @Override public void onConnected(Bundle connectionHint) { mLastLocation = LocationServices.FusedLocationApi.getLastLocation( mGoogleApiClient); if (mLastLocation != null) { mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude())); mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude())); } } } 

Pasos simples para obtener la ubicación actual en el mapa de google:

1 – crear actividad de mapa, de modo que en el método onMap ready cree LocationManager y LocationListener

2 – en “OnMap ready” también verificas la versión de Android y el permiso de usuario ==> si hay un permiso para actualizar la ubicación O pides permiso al usuario

3 – en la clase principal, compruebe el resultado del permiso (onRequestPermissionsResult) ==> si la condición es verdadera, así que proporcione la actualización de la ubicación

4 – en el método (onLocationChanged) creamos la variable LatLng y obtenemos las coordenadas de la ubicación desde mMap we (addMarker y moveCamera) para la variable que acabamos de crear, esto nos da la ubicación cuando el usuario se mueve, por lo que aún necesitamos crear una nueva LatLng en onMap listo para tener la ubicación del usuario cuando la aplicación comienza ==> condición interna si hay permiso (lastKnownLocation).

NOTA:

1) No olvides pedir permisos (Ubicación e Internet) en Manifiesto

2) No olvides tener la clave del mapa de las API de Google

3) Usamos (mMap.clear) para evitar repetir el marcador cada vez que ejecutamos la aplicación o la ubicación de actualización.

Parte de encoding :

 public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; LocationManager locationManager; LocationListener locationListener; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @SuppressLint("MissingPermission") @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { mMap.clear(); LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude()); mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker")); mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation)); Toast.makeText(MapsActivity.this, userLocation.toString(), Toast.LENGTH_SHORT).show(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; if (Build.VERSION.SDK_INT < 23 ){ locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); }else if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()); mMap.clear(); mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker")); mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation)); Toast.makeText(MapsActivity.this, userLocation.toString(), Toast.LENGTH_SHORT).show(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); } } } } 
 //check this condition if (Build.VERSION.SDK_INT < 23 ) 

En algunos estudios Android no funciona mientras el código Whole está funcionando, así que reemplace esta línea por esto:

 if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 

y mi proyecto está funcionando bien.