my code is here:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(false);
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
It only get coordinate when I connected to internet.
You can use android GPS service to get Longitute and Latitute too,
add the permission in your AndroidMenifest.xml,
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Initialization,
// saving the context for later use
private final Context mContext;
// if GPS is enabled
boolean isGPSEnabled = false;
// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;
// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 30000;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;
// Declaring a Location Manager
protected LocationManager mLocationManager;
// This is constructor to get System Location services,
public GPSService(Context context) {
this.mContext = context;
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
}
Checking if GPS managed to fetch the data,
try {
// Getting GPS status
isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
Related
I am trying to create an app which gets latitude and longitude from user's gps this is the class that I am using :-
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
// 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;
// First get location from Network Provider
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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 TODO;
Toast.makeText(this,"It's very important that you agree to gps permission, kindly restart the app and accept",Toast.LENGTH_LONG).show();
}
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;
}
when I call this function in MainActivity it never asks for any permissions and also doesn't show any errors this is the function that I am using :-
String getlocurl(){
GPSTracker gps;
gps = new GPSTracker(MainActivity.this);
double latitude = 0;
double longitude = 0;
if(gps.canGetLocation()){
latitude = gps.getLatitude();
longitude = gps.getLongitude();
String lat = String.valueOf(latitude);
String lng = String.valueOf(longitude);
String mapurl = "https://www.google.com/maps/preview/#"+lat+","+lng+","+"8z";
return mapurl;
}
else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
return "error";
}
}
This is the result that I get : "https://www.google.com/maps/preview/#0.0,0.0,8z"
it returns 0.0,0.0 as latitude and longitude, how do I fix this?
Put this on your Manifest file before the application tag:
<uses-permission android:name="android.permission.INTERNET" /> <!-- verify if connected to the internet -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- verify if connected to any network -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- verify location using GPS, give precise location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- verify location using WiFi and mobile, gives approximate location -->
I found a great function which gives me possibility to get Location quickly.
After that i want to display its (longitude and latitude) but it doest work still i get 0.0 / 0.0.
here's code
What should i do if i want display this latitude and longitude mostly I'm interested in function getLastKnownLocation because i want display this data without using GPS or Internet
public class MainActivity extends Activity implements OnClickListener
{
private static final long MIN_TIME_BW_UPDATES = 0;
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
public EditText lokalizacja;
public Button pobierz;
private static Context context;
LocationManager locationManager;
// 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
public static Context getContext()
{
return context;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lokalizacja = (EditText) findViewById(R.id.editText1);
pobierz = (Button) findViewById(R.id.button1);
pobierz.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.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, (LocationListener) this);
Log.d("Network", "Network Enabled");
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, (LocationListener) this);
Log.d("GPS", "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();
}
String napis = String.valueOf(latitude+ "\n" + longitude);
lokalizacja.setText(napis);
return location;
}
}
As flow never enter the else part due the following condition
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
You need to have condition something like this
if (!isGPSEnabled || !isNetworkEnabled) {
// no network provider is enabled
} else {
or first check for GPS and then after network
For the first time, for getting your current location, you want to enable gps or network in your device. After getting lat and lng create a preference and save these values to preference. So make some changes in your getLocation() method.
If gps and network are disable try to return the saved value from preference.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
I wrote a program that provides the user's position with in a building but not the actual position . I Know that Gps does not provide high accurate result with in building . My code is as follows:
public class Internet extends Service implements LocationListener {
Context context;
LocationManager locationManager;
public Internet(Context context) {
this.context = context;
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
}
Location findMeInternet() {
Boolean isInternet = false;
Location location;
isInternet = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isInternet) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 3, 1, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return location;
}
}
return null;
}
//other override methods with empty bodies .
}
Try GPS provider instead of NetWORK provider ,
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
Make sure that device GPS is enabled. (If someone needs to downvote, please mention the reason also)
I am having an unusually difficult time getting correct "satellites in use" and "satellites in view" integers from my GPS implementation. I have reviewed numerous relevant Stackoverflow threads with no immediate enlightenment. Below is what I have so far that "should" work, however it does not. I've rebuilt this several times from different perspectives without getting either the number of satellites in use or satellites in view. Thanks in advance...
public class GpsData extends Service implements LocationListener {
private GpsStatus mGpsStatus;
private final Context mContext;
boolean isGPSEnabled = false; // flag for GPS status
boolean isNetworkEnabled = false; // flag for network status
boolean canGetLocation = false; // flag for GPS status
Location location; // location
double dLatitude, dAltitude, dLongitude, dAccuracy, dSpeed, dSats;
float fAccuracy, fSpeed;
long lSatTime; // satellite time
String szSignalSource, szAltitude, szAccuracy, szSpeed;
public String szSatellitesInView;
public String szSatellitesInUse;
public static String szSatTime;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 0 meters
private static final long MIN_TIME_BW_UPDATES = 1000; //1 sec
protected LocationManager locationManager;
protected GpsListener gpsListener = new GpsListener();
public GpsData(Context context) {
this.mContext = context;
getLocation();
locationManager.addGpsStatusListener(gpsListener);
}
class GpsListener implements GpsStatus.Listener{
#Override
public void onGpsStatusChanged(int event) {
int iCountInView = 0;
int iCountInUse = 0;
mGpsStatus = locationManager.getGpsStatus(mGpsStatus);
Iterable<GpsSatellite> satellites = mGpsStatus.getSatellites();
if (satellites != null) {
for (GpsSatellite gpsSatellite : satellites) {
iCountInView++;
if (gpsSatellite.usedInFix()) {
iCountInUse++;
}
}
}
{
{
szSatellitesInView = String.valueOf(iCountInView);
szSatellitesInUse = String.valueOf(iCountInUse);
}
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS satellite status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting cellular network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.addGpsStatusListener(gpsListener);//needed?
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Cell tower", "Cell tower");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
dLatitude = location.getLatitude();
dLongitude = location.getLongitude();
lSatTime = location.getTime();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.addGpsStatusListener(gpsListener);
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) {
dLatitude = location.getLatitude();
dLongitude = location.getLongitude();
lSatTime = location.getTime();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
Got it.
public class GpsData extends Service implements LocationListener {
boolean isGPSEnabled = false; // flag for GPS satellite status
boolean isNetworkEnabled = false; // flag for cellular network status
boolean canGetLocation = false; // flag for either cellular or satellite status
private GpsStatus mGpsStatus;
private final Context mContext;
protected LocationManager locationManager;
protected GpsListener gpsListener = new GpsListener();
Location location; // location
double dLatitude, dAltitude, dLongitude, dAccuracy, dSpeed, dSats;
float fAccuracy, fSpeed;
long lSatTime; // satellite time
String szSignalSource, szAltitude, szAccuracy, szSpeed;
public String szSatellitesInUse, szSatellitesInView;
public static String szSatTime;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 0 meters
private static final long MIN_TIME_BW_UPDATES = 1000; //1 second
public GpsData(Context context) {
this.mContext = context;
getLocation();
}
class GpsListener implements GpsStatus.Listener{
#Override
public void onGpsStatusChanged(int event) {
}
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);// getting GPS satellite status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);// getting cellular network status
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {//GPS is enabled, getting lat/long via cellular towers
locationManager.addGpsStatusListener(gpsListener);//inserted new
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Cell tower", "Cell tower");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
szAltitude = " NA (using cell towers)";
szSatellitesInView = " NA (using cell towers)";
szSatellitesInUse = " NA (using cell towers)";
}
}
}
if (isGPSEnabled) {//GPS is enabled, gettoing lat/long via satellite
if (location == null) {
locationManager.addGpsStatusListener(gpsListener);//inserted new
locationManager.getGpsStatus(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) {
dAltitude = location.getAltitude();
szAltitude = String.valueOf(dAltitude);
/**************************************************************
* Provides a count of satellites in view, and satellites in use
**************************************************************/
mGpsStatus = locationManager.getGpsStatus(mGpsStatus);
Iterable<GpsSatellite> satellites = mGpsStatus.getSatellites();
int iTempCountInView = 0;
int iTempCountInUse = 0;
if (satellites != null) {
for (GpsSatellite gpsSatellite : satellites) {
iTempCountInView++;
if (gpsSatellite.usedInFix()) {
iTempCountInUse++;
}
}
}
szSatellitesInView = String.valueOf(iTempCountInView);
szSatellitesInUse = String.valueOf(iTempCountInUse);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
I want to get the Location object on Button press.
I know the LocationListener callbacks, however they execute only after a particular time or distance. I want to get Location instantaneously. Are there any methods to do so.
public class GPSHelper {
private Context context;
// flag for GPS Status
private boolean isGPSEnabled = false;
// flag for network status
private boolean isNetworkEnabled = false;
private LocationManager locationManager;
private Location location;
private double latitude;
private double longitude;
public GPSHelper(Context context) {
this.context = context;
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
} public void getMyLocation() {
List<String> providers = locationManager.getProviders(true);
Location l = null;
for (int i = 0; i < providers.size(); i++) {
l = locationManager.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
if (l != null) {
latitude = l.getLatitude();
longitude = l.getLongitude();
}
}
public boolean isGPSenabled() {
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return (isGPSEnabled || isNetworkEnabled);
}
/**
* Function to get latitude
*/
public double getLatitude() {
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
return longitude;
}
You are welcome to call getLastKnownLocation() on LocationManager to retrieve the last known location for your requested location provider. However:
that location may be old
that location may be null
Hence, your code will need to be able to cope with both of those scenarios.
Use LocationManager class:
locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude=location.getLatitude();
longitude=location.getLongitude();
Log.d("old","lat : "+latitude);
Log.d("old","long : "+longitude);
this.onLocationChanged(location);
}
Try the following:
https://github.com/delight-im/Android-SimpleLocation
If your location is enabled, you need just 3 lines of code:
SimpleLocation location = new SimpleLocation(this); //or context instead of this
double latitude = location.getLatitude();
double longitude = location.getLongitude();
You can get the last known location using FusedLocationProviderClient
There are very simple steps to get current latitude, longitude, altitude & bearing
Update or install Google Play services to the current latest version in your SDK Manager.
Add Location permission into your project's manifest.
Add this line into your Activity/Fragment:
(i) Code For Kotlin
private lateinit var fusedLocationClient: FusedLocationProviderClient
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
Log.d(TAG, "latitude:" + location?.latitude)
Log.d(TAG, "longitude:" + location?.longitude)
Log.d(TAG, "altitude:" + location?.altitude)
Log.d(TAG, "bearing:" + location?.bearing)
}
(ii) Code for JAVA
private FusedLocationProviderClient fusedLocationClient;
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
Log.d(TAG,location.getLatitude)
Log.d(TAG,location.getLongitude)
}
}
});
That's it. Run your code and you can check your current location in Logcat. Don't forget to accept location permission from your emulator or Android phone.
You can not get proper altitude and bearing using FusedLocationProviderClient.
Happy Coding :)