I am building an app which can detect location change by reading GPS data. I am observing the change on longitude and latitude to detect the location change. But my app is only working when I go far away. The value I get on latitude and longitude is only upto two decimal points.Is there any way to get more precise data of latitude and longitude in android? I want get the value upto 7 or 8 decimal point. My code is given below-
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.d("GPS ", "ON");
mysample = mysample + "GPS = 1 \n";
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latitude = 0;
double longitude = 0;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
if ( plat != latitude || plong != longitude) {
Log.d("GPS MOVING ", "ON");
mysample = mysample + "GPS MOVING = 1 \n";
Log.d("GPS CORDINATE ", "" + longitude + "" + latitude);
plat = latitude;
plong = longitude;
} else {
Log.d("GPS MOVING ", "OFF");
mysample = mysample + "GPS MOVING = 0 \n";
Log.d("GPS CORDINATE ", "" + longitude + "" + latitude);
}
} else {
Log.d("GPS ", "OFF");
mysample = mysample + "GPS = 0 \n";
Log.d("GPS MOVING ", "OFF");
mysample = mysample + "GPS MOVING = 0 \n";
}
Getting precise data of latitude and longitude is a nice idea however, setting location results to 7 or 8 decimal points is practically used in surveying purposes, as shown in Decimal degrees in Wikipedia.
A perfect explanation for this concern can be found in this thread.
Also, please check solution given in this SO post - How to better handle GPS location and android. Hope it helps!
Related
This question already has answers here:
How to calculate distance between two locations using their longitude and latitude value
(14 answers)
Closed 6 years ago.
I want your help to calculate the distance b/t two longitudes. Can anybody tell me how to find the distance? I am new on Android studio. I want to find the distance in my app. Destination address in defined by mlat and mlong and current address is calculated through GPS whose value goes in longitude and latitude.
My code is:
double mlat =30.726030;
double mlong=76.759268;
imgButton1 =(ImageButton)findViewById(R.id.imageButton1);
mgButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Location gpsLocation = appLocationService.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
String result = "Latitude: " + gpsLocation.getLatitude() +
" Longitude: " + gpsLocation.getLongitude();
tvAddress.setText(result);
} else {
showSettingsAlert();
}
}
});
Tell me how to find the distance between two longitudes and latitudes.
Use the distanceBetween method to calculate distance:
Location.distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)
I have an application where I need to get my current location I am using
setNlocation(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
Because of this I am getting last location I also try to use
#Override
public void onLocationChanged(Location loc)
{
glat = loc.getLatitude();
glng = loc.getLongitude();
Toast.makeText( getApplicationContext(),"GPS Lat:" + glat + "GPS Lng" + glng,Toast.LENGTH_LONG).show();
}
but that GPS icon is blinking and blinking and blinking .(Not getting GPS Lat Lng of current position)
Here is small application with step by step description to gets current locations GPS co-ordinate
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,locationListener);
I trying to match hardcoded latitude an longitude with dynamic latitude and longitude, but its not showing correct output, can anyone help me to sort out this error
My code is
String Log = "-122.084095";
String Lat = "37.422005";
try {
if ((Lat.equals(latitude)) && (Log.equals(longitude))) {
AudioManager audiM = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audiM.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(getApplicationContext(),
"You are at home",
Toast.LENGTH_LONG).show();
} else {
AudioManager auMa = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
auMa.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(getApplicationContext(),
"You are at office ", Toast.LENGTH_LONG)
.show();
}
} catch (Exception e) {
e.printStackTrace();
}
it always goes for else part...
You don't want to use a String comparison here as you can't guarantee the level of accuracy with the real-time location.
The best way to handle this would be to determine the distance between the points and then determine if it's close enough for you to consider, approx, the same.
For this, we use distanceBetween or distanceTo
Docs are here and here
Examples can be found here. Here's one of those examples:
Location locationA = new Location("point A");
locationA.setLatitude(pointA.getLatitudeE6() / 1E6);
locationA.setLongitude(pointA.getLongitudeE6() / 1E6);
Location locationB = new Location("point B");
locationB.setLatitude(pointB.getLatitudeE6() / 1E6);
locationB.setLongitude(pointB.getLongitudeE6() / 1E6);
double distance = locationA.distanceTo(locationB);
The latitude and longitude are variables which vary from point to point, matter of fact they keep on changing while standing on the same spot, because it is not precise.
Instead of comparing the Strings, take a rounded value of the lat and long (in long or float ) and check those values within a certain range. That will help you out with the "Home" and "Office " thing.
For e.g :
String Log = "22.084095";
String Lat = "37.422005";
double lng=Double.parseDouble(Log);
double lat=Double.parseDouble(Lat);
double upprLogHome=22.1;
double lwrLogHome=21.9;
double upprLatHome=37.5;
double lwrLatHome=37.3;
// double upprLogOfc=;
// double lwrLogOfc=;
// double upprLatOfc=;
// double lwrLatOfc=;
if(lng<upprLogHome && lng>lwrLogHome && lat<upprLatHome &&lat>lwrLatHome )
{
System.out.println("You are Home");
}
/* else if(lng<upprLogOfc && lng>lwrLogOfc && lat<upprLatOfc &&lat>lwrLatOfc )
{
System.out.println("You are Home");
}*/
else
System.out.println("You are neither Home nor Ofc");
But for the negative lat long you have to reverse the process of checking.
your matching is okay but you probably should not check for a gps location like this.
You should convert the location to something where you can check that you are in 10m radius of the location.
A nicer way would be to leave the long/lat as doubles and compare the numbers.
if(lat > HOME_LAT - 0.1 && lat < HOME_LAT + 0.1 && ...same for lon... ){}
Try this,
Use google map api to pass lat and long value you will get formatted address. And also pass dynamic lat and lng value same google api you will get formatted address. And then match two formatted address you will get result. i suggest this way you can try this
Use this google api. http://maps.googleapis.com/maps/api/geocode/json?latlng=11.029494,76.954422&sensor=true
Reena, its very easy, Check out below code. You need to use "equalsIgnoreCase()" instead of
"equals".
if ((Lat.equalsIgnoreCase(latitude)) && (Log.equalsIgnoreCase(longitude))) {
should work
Example below :
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}
You can print dynamice Latitute and Longitute to Logcat and check with hardcoded Latitute and Longitute
I use the following method to get the current latitude & longitude:
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager == null) {
Toast.makeText(LocationsListActivity.this,
"Location Manager Not Available", Toast.LENGTH_SHORT)
.show();
}
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
but the problem the lat and lng I got only have 8 numbers behind the decimal (lat: 52.51491445, lng: 13.39044515)
What I wanna have is the lat and lng I got has 13 numbers behind the decimal.
How can I do that?
Thanks
You could look into the setAccurary() method and the setPowerRequirement() method of Criteria.
I'm trying to get the latitude and longitude information from an android phone through GPS, when i'm outdoor or under the sky directly i'm able to get the values instantly but when i'm indoor or inside a room its taking more than a minute to get the values. Can anyone help me in getting this values fastly when I'm using my app inside a room.
I'm using the following code in getting the values:
LocationManager locManager;
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f,
locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
and
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
EditText myLocationText = (EditText)findViewById(R.id.editText1);
EditText myLocationText1 = (EditText)findViewById(R.id.editText2);
String latString = "";
String LongString = "";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latString = "" + lat;
LongString ="" + lng;
} else {
latString = "No location found";
LongString = "No location found";
}
myLocationText.setText(""+ latString);
myLocationText1.setText(""+ LongString);
}
Is there any other way in getting the GPS values other than using LocationManager??
You can get the last known location, and it's quite fast:
/**
* Gets the last known location.
*
* #param locationManager the location manager
* #return the last known location
*/
public static Location getLastKnownLocation(LocationManager locationManager)
{
Location bestResult = null;
float bestAccuracy = 10000;
long bestTime = 0;
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
Log.d("LOCATION", "Provider: " + provider);
Location location = locationManager.getLastKnownLocation(provider);
Log.d("LOCATION", "Location found? "+ (location==null?"NO":"YES"));
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
Log.d("LOCATION", "Acc: "+ String.valueOf(accuracy) + " -- Time: " + String.valueOf(time));
if ((time > minTime && accuracy < bestAccuracy)) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
}
else if (time < minTime &&
bestAccuracy == Float.MAX_VALUE && time > bestTime){
bestResult = location;
bestTime = time;
}
}
}
Log.d("LOCATION", "BEST FOUND? "+ (bestResult==null?"NO":"YES"));
return bestResult;
}
You can get the last known location of the device using the following method in LocationManager, this is the location that has been last found system-wide.
This method is the key:
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
See for more details Obtaining User Location
If you are indoors, you would be better of using LocationManager.NETWORK_PROVIDER as you are unlikely to get a signal inside. You could also use getLastKnownLocation(), but this may be non existent or out of date.
If you want get position in a room, gps provider is slowly. You can try changing:
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f,
locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
By:
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000L,500.0f,
locationListener);
And you will receive location in 'public void onLocationChanged(Location location)' method.
I used Network provider to fetch the Co-Ordinates and it is always much faster inside the house in living room. But when I try the same in the Basement area, it doesn't fetch the coordinates at all though I waited almost couple of minutes.
Note: I could able to make a call from basement area and I am also able to browse as well..