how to get current location in google map android
Actually my problem is I am not getting current location latitude and longitude I tried so many ways.I know that this question already asked in SO I tried that answers also still I didn't get answer.Please help me Code:
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));
Solution 1:
Please check the sample code for the Google Maps Android API v2. Using this will solve your problem.
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) {
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
}
});
}
}
}
Call this function in onCreate
function.
Update:
The method mMap.setOnMyLocationChangeListener is now deprecated, you need to use the FusedLocationProviderClient
now.
private FusedLocationProviderClient fusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
To request the last known location, call the getLastLocation() method. The following code snippet illustrates the request and a simple handling of the response:
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});
Reference: https://developer.android.com/training/location/retrieve-current.html
Solution 2:
I think that better way now is:
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
Documentation. Getting the Last Known Location
Solution 3:
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;
}
}