My GPS provider is enabled but I get null location nonetheless - android

I'm using this code to get the geo-position of the user
public Location getLocation() {
Location location = null;
double lat;
double lng;
try {
LocationManager mLocationManager = (LocationManager) con.getSystemService(LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else {
// First get location from Network Provider
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, this);
Log.d("Network", "Network");
if (mLocationManager != null) {
location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
System.out.println(lat);
}
}
}
//get the location by gps
if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
Log.d("GPS Enabled", "GPS Enabled");
if (mLocationManager != null) {
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
System.out.println(lat);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
An this is what I get:
Network
39.68967
Gps Enabled
(nothing)
I can't understand the reason why Gps is enabled and I still can't get the coordinates from the gps provider

I just finished creating a sample project for understanding the usage of Location Services. I am just posting my code, feel free to use it for your need and understanding the working of Location Services.
public class DSLVFragmentClicks extends Activity implements LocationListener {
private final int BESTAVAILABLEPROVIDERCODE = 1;
private final int BESTPROVIDERCODE = 2;
LocationManager locationManager;
String bestProvider;
String bestAvailableProvider;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BESTPROVIDERCODE) {
if (resultCode!= Activity.RESULT_OK || locationManager.isProviderEnabled(bestProvider)) {
Toast.makeText(getActivity(), "Error! Location Service " + bestProvider + " not Enabled", Toast.LENGTH_LONG).show();
} else {
getLocation(bestProvider);
}
} else {
if (resultCode!= Activity.RESULT_OK || locationManager.isProviderEnabled(bestAvailableProvider)) {
Toast.makeText(getActivity(), "Error! Location Service " + bestAvailableProvider + " not Enabled", Toast.LENGTH_LONG).show();
} else {
getLocation(bestAvailableProvider);
}
}
}
public void getLocation(String usedLocationService) {
Toast.makeText(getActivity(), "getting Location", Toast.LENGTH_SHORT).show();
long updateTime = 0;
float updateDistance = 0;
// finding the current location
locationManager.requestLocationUpdates(usedLocationService, updateTime, updateDistance, this);
}
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.main);
// set a Criteria specifying things you want from a particular Location Service
Criteria criteria = new Criteria();
criteria.setSpeedRequired(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);
criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
criteria.setAltitudeRequired(false);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
// finding best provider without fulfilling the criteria
bestProvider = locationManager.getBestProvider(criteria, false);
// finding best provider which fulfills the criteria
bestAvailableProvider = locationManager.getBestProvider(criteria, true);
String toastMessage = null;
if (bestProvider == null) {
toastMessage = "NO best Provider Found";
} else if (bestAvailableProvider != null && bestAvailableProvider.equals(bestAvailableProvider)) {
boolean enabled = locationManager.isProviderEnabled(bestAvailableProvider);
if (!enabled) {
Toast.makeText(getActivity(), " Please enable " + bestAvailableProvider + " to find your location", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(mainIntent, BESTAVAILABLEPROVIDERCODE);
} else {
getLocation(bestAvailableProvider);
}
toastMessage = bestAvailableProvider + " used for getting your current location";
} else {
boolean enabled = locationManager.isProviderEnabled(bestProvider);
if (!enabled) {
Toast.makeText(getActivity(), " Please enable " + bestProvider + " to find your location", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(mainIntent, BESTPROVIDERCODE);
} else {
getLocation(bestProvider);
}
toastMessage = bestProvider + " is used to get your current location";
}
Toast.makeText(getActivity(), toastMessage, Toast.LENGTH_LONG).show();
return true;
}
});
}
#Override
public void onLocationChanged(Location location) {
Log.d("Location Found", location.getLatitude() + " " + location.getLongitude());
// getting the street address from longitute and latitude
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
String addressString = "not found !!";
try {
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
StringBuilder stringBuilder = new StringBuilder();
if (addressList.size() > 0) {
Address address = addressList.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName()).append("\n");
}
addressString = stringBuilder.toString();
locationManager.removeUpdates(this);
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Toast.makeText(getActivity(), " Your Location is " + addressString, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void onProviderEnabled(String s) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void onProviderDisabled(String s) {
//To change body of implemented methods use File | Settings | File Templates.
}
}
If you didn't understand any part of it then feel free to ask.

// Use LocationManager.NETWORK_PROVIDER instead of GPS_PROVIDER.
public Location getLocation(){
try{
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}catch (Exception e) {
e.printStackTrace();
}
if(locationManager != null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
}
return location;
}

Related

Fetching latitude and longitude programmaticaly in android always getting GPS LastKnownLocation null

Hello all i know this question is too old and there are many of them but none of the solution is working for me. I am fetching latitude and longitude programmaticaly i tried below code but what is happening is for GPS every time i am getting LastKnownLocation = null also my GPS is enabled on my device, i tried this code on different devices where on some of them i am able to get latitude and longitude from GPS but for most of them it is showing null. I don't know why this code is failing for most of the cases, if any one of you know anything about this or any better way of doing it then please tell me i have spent almost a week digging what's wrong in the above code but nothing help me out.
UPDATE- Is google's FusedLocationApi free or there is limited requests per day ??
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isGPSEnabled) {
Log.d("gps", "gpsenabled");
if (location == null) {
Log.d("gps", "location is null");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
Log.d("gps", "locationManager is not null");
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.d("gps", "location is not null");
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("gps", "lat: " + latitude + ", lon: " + longitude);
}
}
}
}
if (isNetworkEnabled) {
Log.d("gps", "networkenabled");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
Log.d("gps", "locationManager is not null");
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.d("gps", "location is not null");
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("gps", "lat: " + latitude + ", lon: " + longitude);
}
}
}
//
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = lm.getBestProvider(criteria, false);
Log.d("gps", "bestProvider: " + bestProvider);
Location location = lm.getLastKnownLocation(bestProvider);
Log.d("gps", "lat: " + location.getLatitude() + ", lon: " + location.getLongitude());
//
}
} catch (Exception e) {
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
latitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to setttings menu ?");
alertDialog.setPositiveButton("Setting", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
this.location = location;
latitude = getLatitude();
longitude = getLongitude();
Log.d("gps", "onLocationChanged");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}

Android Geocoder doesn't work on API 23

i have develop app that when run take the city name by lat and long using a GPSTracker.java class and add this city name to url for retrive json data.
My code works very fine from API 18 to API 22 but now when i run my code on API 23 the geocoder doesn't work and city name is null
This is my code on Main Activity for retrive city name:
// To get City-Name from coordinates
GPSTracker gpsTracker = new GPSTracker(getActivity());
String cityName = null;
Geocoder gcd = new Geocoder(getContext(), Locale.ENGLISH);
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
Log.d("nome_cit", "debug_cit " + cityName);
// Controllo formattazione nomi Car2Go
if(cityName.equals("Rome")) {
nome_citta = "Roma";
}else if (cityName.equals("Florence")){
nome_citta = "Firenze";
}
else if (cityName.equals("Milan")){
nome_citta = "Milano";
}
else if (cityName.equals("Turin")){
nome_citta = "Torino";
}else if (cityName.equals("New York")){
nome_citta = "NewYorkCity";
}else if (cityName.equals("Los Angeles")){
nome_citta = "LosAngeles";
}
else if (cityName.equals("San Diego")){
nome_citta = "SanDiego";
}
else if (cityName.equals("Twin Cities")){
nome_citta = "TwinCities";
}
else if (cityName.equals("Vienna")) {
nome_citta = "wien";
}
else if (cityName.equals("Munich")) {
nome_citta = "München";
}
else if (cityName.equals("Osler")) {
nome_citta = "Rheinland";
}
// Controllo formattazione JCDecaux
else if (cityName.equals("Valencia")) {
nome_citta_test = "Valence";
}
else if (cityName.equals("Parigi")) {
nome_citta_test = "Paris";
}
else if (cityName.equals("Besançon")){
nome_citta_test = "Besancon";
}
else if (cityName.equals("Créteil")) {
nome_citta_test = "Creteil";
}
else {
nome_citta = cityName;
nome_citta_test = cityName;
}
}
else {
}
} catch (IOException e) {
e.printStackTrace();
}
on my map for my position i have set this permission:
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager
.PERMISSION_GRANTED && ActivityCompat
.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager
.PERMISSION_GRANTED) {
/*Toast.makeText(getActivity(),
"Need location permission for map.setMyLocationEnabled(true);",
Toast.LENGTH_LONG).show();*/
MultiplePermissionsListener snackbarMultiplePermissionsListener =
SnackbarOnAnyDeniedMultiplePermissionsListener.Builder
.with((ViewGroup) getView(), "La app ha bisogno di ablitare i permessi di localizzaione per mostrare la mappa")
.withOpenSettingsButton("Settings")
.withCallback(new Snackbar.Callback() {
#Override
public void onShown(Snackbar snackbar) {
// Event handler for when the given Snackbar has been dismissed
}
#Override
public void onDismissed(Snackbar snackbar, int event) {
// Event handler for when the given Snackbar is visible
}
})
.build();
Dexter.checkPermissions(snackbarMultiplePermissionsListener, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE, Manifest.permission.GET_ACCOUNTS);
return;
}
and this is my GPSTracker.java class:
public final class GPSTracker implements LocationListener {
private final Context mContext;
// flag for GPS status
public boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
/**
* Function to get the user's current location
*
* #return
*/
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("isGPSEnabled", "=" + isGPSEnabled);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.v("isNetworkEnabled", "=" + isNetworkEnabled);
if (isGPSEnabled == false && isNetworkEnabled == false) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
location=null;
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
location=null;
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
// DecimalFormat latitude = new DecimalFormat("00.00");
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle(R.string.title);
// Setting Dialog Message
alertDialog
.setMessage(R.string.subtitle);
// On pressing Settings button
alertDialog.setPositiveButton(R.string.impostazioni,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton(R.string.cancella,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setCancelable(false);
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Also i have notice that using place picker on API 23 i recive this error:
Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
for this code:
if (resultCode == getActivity().RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
String addresses = place.getAddress().toString();
if (addresses != null) {
puntoA.setText(addresses);
}if (addresses.isEmpty()){
addresses = "(" + place.getLatLng().latitude + "," + place.getLatLng().longitude + ")";
puntoA.setText("nessun indirizzo disponibile " + addresses);
}
//puntoA.setText(addresses);
// Recupero coordinate
Geocoder geocoder = new Geocoder(getActivity());
List<Address> address = null;
try {
address = geocoder.getFromLocationName(addresses, 1);
} catch (IOException e) {
e.printStackTrace();
}
if(address.size() > 0) {
Lat = address.get(0).getLatitude();
Lon = address.get(0).getLongitude();
}
else if (address.size() == 0) {
Lat = place.getLatLng().latitude;
Lon = place.getLatLng().longitude;
}
but also this function works very well on other API version
Any help please?
now my code works fine on API 23 and i use this code:
// To get City-Name from coordinates
GPSTracker gpsTracker = new GPSTracker(getActivity());
Double LatFab = gpsTracker.getLatitude();
Double LonFab = gpsTracker.getLongitude();
List<Address> geocodeMatchess = null;
String Country_;
try {
geocodeMatchess = new Geocoder(getActivity(), Locale.ENGLISH).getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
if (geocodeMatchess.isEmpty()) {
}else {
Country_ = geocodeMatchess.get(0).getLocality();
citta_fab = Country_;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hope this hel you

How to get location (lat,lng) in API 23 and above in Android Programmatically?

I am developing an application which enable GPS and get the current location. My code is working fine in all android version expect API 23 i.e. Marshmallows. I am testing in Nexus 5 (API 23), Galaxy Note 3 (API 22).
Here is my code
public void program()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(NearBy.this);
builder.setTitle("Location Service is Not Active");
builder.setMessage("Please Enable your location services").setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
final String cityName = addresses.get(0).getAddressLine(0) + " ";
String stateName = addresses.get(0).getAddressLine(1) + " ";
String countryName = addresses.get(0).getAddressLine(2) + " ";
String country = addresses.get(0).getCountryName() + " ";
String Area = addresses.get(0).getSubAdminArea() + " ";
String Area1 = addresses.get(0).getAdminArea() + " ";
String Area2 = addresses.get(0).getLocality() + " ";
String Area3 = addresses.get(0).getSubLocality();
Log.e("Locaton", cityName + stateName + countryName + country + Area + Area1 + Area2 + Area3);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
I am getting NullpointerException at
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
only in Nexus 5 (API 23). I also granted permission (ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION) in both Mainfest and also during run time.
Kindly provide solution for this.
UPDATED
I have changed my code. I created a GPSTracker class and I am getting lat, Lng as 0
GPSTracker.java
public class GPSTracker extends Activity implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
#TargetApi(Build.VERSION_CODES.M)
public void stopUsingGPS() {
if (locationManager != null) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location currentLocation) {
this.location = currentLocation;
getLatitude();
getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Problem
The location obtained may be null if the last know location could not be found due to various reasons. Read about it in the docs [here][2]
Reason/How i debugged it
getFromLocation does not throws a nullpointer according to documentation hence the problem is in your location object.
Read here about this method
Remedy
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Check if the location obtained in the above step is NOT NULL and then proceed with the geocoder.
Code snippet
...
else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location == null) {
log.d("TAG", "The location could not be found");
return;
}
//else, proceed with geocoding.
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
Fetching the location - An example
Read here
Complete code
View it here
First In marshmallow add all permission on run time also. Otherwise Please restart your mobile and then check again.

Getting coordinates explicitly from GPS provider

I want to achieve something which I though was simple enough, but now I end up being a little confused.
I want to get the coordinates of the user in this way
Is there a GPS provider?
If yes, get the coordinates from gps
Else if there is a network provider get them from there
I used both locationManager and onLocationChange(), and the new API with locationClient but I can't get the coordinates from my device's GPS, only from network.
This is the one with the locationManager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use default
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
// new AlertDialog.Builder(v.getContext()).setMessage("Provider " + provider + " has been selected.").show();
onLocationChanged(location);
System.out.println(location.getLatitude());
Intent intent = new Intent(getApplicationContext(),DriveMeActivity.class);
intent.putExtra("monument", monument);
intent.putExtra("latitude", location.getLatitude());
intent.putExtra("longitude",location.getLongitude());
startActivity(intent);
} else {
new AlertDialog.Builder(con).setMessage("Location not available").show();
System.out.println("Location not available");
System.out.println("Location not available");
}
and this is the one with locationClient
GooglePlayServicesUtil.isGooglePlayServicesAvailable(v.getContext())
if(mLocationClient.getLastLocation()!=null)
Toast.makeText(getApplicationContext(),
mLocationClient.getLastLocation().getLongitude()+ "|" +
mLocationClient.getLastLocation().getLatitude() ,
Toast.LENGTH_SHORT).show();
here's the complete code to find the best available provider whether gps or network and show settings menu to enable the location services.
public class DSLVFragmentClicks extends Activity implements LocationListener {
private final int BESTAVAILABLEPROVIDERCODE = 1;
private final int BESTPROVIDERCODE = 2;
LocationManager locationManager;
String bestProvider;
String bestAvailableProvider;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BESTPROVIDERCODE) {
if (requestCode != Activity.RESULT_OK || locationManager.isProviderEnabled(bestProvider)) {
Toast.makeText(getActivity(), "Error! Location Service " + bestProvider + " not Enabled", Toast.LENGTH_LONG).show();
} else {
getLocation(bestProvider);
}
} else {
if (requestCode != Activity.RESULT_OK || locationManager.isProviderEnabled(bestAvailableProvider)) {
Toast.makeText(getActivity(), "Error! Location Service " + bestAvailableProvider + " not Enabled", Toast.LENGTH_LONG).show();
} else {
getLocation(bestAvailableProvider);
}
}
}
public void getLocation(String usedLocationService) {
Toast.makeText(getActivity(), "getting Location", Toast.LENGTH_SHORT).show();
long updateTime = 0;
float updateDistance = 0;
// finding the current location
locationManager.requestLocationUpdates(usedLocationService, updateTime, updateDistance, this);
}
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.main);
// set a Criteria specifying things you want from a particular Location Service
Criteria criteria = new Criteria();
criteria.setSpeedRequired(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);
criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
criteria.setAltitudeRequired(false);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
// finding best provider without fulfilling the criteria
bestProvider = locationManager.getBestProvider(criteria, false);
// finding best provider which fulfills the criteria
bestAvailableProvider = locationManager.getBestProvider(criteria, true);
String toastMessage = null;
if (bestProvider == null) {
toastMessage = "NO best Provider Found";
} else if (bestAvailableProvider != null && bestAvailableProvider.equals(bestAvailableProvider)) {
boolean enabled = locationManager.isProviderEnabled(bestAvailableProvider);
if (!enabled) {
Toast.makeText(getActivity(), " Please enable " + bestAvailableProvider + " to find your location", Toast.LENGTH_LONG).show();
// show settings menu to start gps or network location service
Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(mainIntent, BESTAVAILABLEPROVIDERCODE);
} else {
getLocation(bestAvailableProvider);
}
toastMessage = bestAvailableProvider + " used for getting your current location";
} else {
boolean enabled = locationManager.isProviderEnabled(bestProvider);
if (!enabled) {
Toast.makeText(getActivity(), " Please enable " + bestProvider + " to find your location", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(mainIntent, BESTPROVIDERCODE);
} else {
getLocation(bestProvider);
}
toastMessage = bestProvider + " is used to get your current location";
}
Toast.makeText(getActivity(), toastMessage, Toast.LENGTH_LONG).show();
return true;
}
});
}
#Override
public void onLocationChanged(Location location) {
Log.d("Location Found", location.getLatitude() + " " + location.getLongitude());
// getting the street address from longitute and latitude
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
String addressString = "not found !!";
try {
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
StringBuilder stringBuilder = new StringBuilder();
if (addressList.size() > 0) {
Address address = addressList.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName()).append("\n");
}
addressString = stringBuilder.toString();
locationManager.removeUpdates(this);
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Toast.makeText(getActivity(), " Your Location is " + addressString, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void onProviderEnabled(String s) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void onProviderDisabled(String s) {
//To change body of implemented methods use File | Settings | File Templates.
}
}
I have already explained a lot in comments but if you still don't understand something then feel free to ask.
I hope you are trying it on a device and you have tried it out in open. In most cases You won't get gps coordinates until you step out.
Most probably you don't have the location fix and GPS locationProvider takes time to get the location fix in compare to network location provider.
What can you do is that you can use the last known location fix.
String locationProvider = LocationManager.GPS_PROVIDER;
// Or use LocationManager.NETWORK_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
But the further problem is that you might have the old location fix and network provider can provide you better location.
Android has really good documentation on this and sample code to find the best known location.
http://developer.android.com/guide/topics/location/strategies.html

How to get complete details of current location using GPS & Location Manager

I am using GPS to get longitude and latitude of a location, but now I want to get each and every detail of location like: country, city, state, zip code, street number and so on.
Maximum details of current location.
Code:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
String country;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled
(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation
(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation
(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
private void initmainIntent() {
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
if (location != null) {
Geocoder gcd = new Geocoder(getApplicationContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses.size() > 0) {
String s = "Address Line: "
+ addresses.get(0).getAddressLine(0) + "\n"
+ addresses.get(0).getFeatureName() + "\n"
+ "Locality: "
+ addresses.get(0).getLocality() + "\n"
+ addresses.get(0).getPremises() + "\n"
+ "Admin Area: "
+ addresses.get(0).getAdminArea() + "\n"
+ "Country code: "
+ addresses.get(0).getCountryCode() + "\n"
+ "Country name: "
+ addresses.get(0).getCountryName() + "\n"
+ "Phone: " + addresses.get(0).getPhone()
+ "\n" + "Postbox: "
+ addresses.get(0).getPostalCode() + "\n"
+ "SubLocality: "
+ addresses.get(0).getSubLocality() + "\n"
+ "SubAdminArea: "
+ addresses.get(0).getSubAdminArea() + "\n"
+ "SubThoroughfare: "
+ addresses.get(0).getSubThoroughfare()
+ "\n" + "Thoroughfare: "
+ addresses.get(0).getThoroughfare() + "\n"
+ "URL: " + addresses.get(0).getUrl();
locationNotFound.setVisibility(View.GONE);
locationFound.setVisibility(View.VISIBLE);
foundLocationText.setText(s);
}
} catch (IOException e) {
e.printStackTrace();
}
background(location.getLatitude(), location.getLongitude());
}
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
}
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
public boolean getLocation(Context context, LocationResult result) {
// I use LocationResult callback class to pass location value from
// MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListenerGps);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
if (location != null) {
System.out.println(location.getLatitude());
}
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
Here is the Tutorial to Get Current location and City name using GPS
Once you get GPS co-ordinates
By using Geocoder class you can every details
See below code snip is for getting Current City Same way you can go for other details also.
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(
getBaseContext(),
"Location changed : Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Currrent City is: "
+ cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Update (as per comment)
If you want to send this details to any contact via SMS.
I would say this page may help you
Using this code you can find the address like street, State, Country and Pin.
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
String address = "";
if (addresses != null && addresses.size() >= 0) {
address = addresses.get(0).getAddressLine(0);
if (addresses != null && addresses.size() >= 1) {
address += ", " + addresses.get(0).getAddressLine(1);
}
if (addresses != null && addresses.size() >= 2) {
address += ", " + addresses.get(0).getAddressLine(2);
}
}
And you need to run this code in separate thread or in AsyncTask because it will internally call the network connection.
I somehow spent many hours to complete this task. In the below code the onMapReady device location is detected and shows a marker at that location. On click on the marker the location address is shown.
public class StoreFinder extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private static final int Request_User_Location_Code = 99;
private double latitude;
double longitude;
private int ProximityRadius = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkUserLocationPermission();
}
// 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 (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public boolean checkUserLocationPermission()
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
return false;
}
else
{
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode)
{
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if (googleApiClient == null)
{
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else
{
Toast.makeText(this, "Permission Denied...", Toast.LENGTH_SHORT).show();
}
return;
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
lastLocation = location;
if (currentUserLocationMarker != null)
{
currentUserLocationMarker.remove();
}
/*----------to get City-Name from coordinates ------------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(latitude, latitude, 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getAddressLine(0);
} catch (IOException e) {
e.printStackTrace();
}
String s = cityName;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(s);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
currentUserLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(16));
if (googleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, (LocationListener) this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}

Categories

Resources