How to use coarse location to compare with saved location in database - android

I am writing an android app where a user will geolocate using coarse location using Network Location. I want the user to be able to save a location at a particular time into a db (savedLocation), and then if the user returns to savedLocation, (or within a coarse range of that location since i'm suing network location) I want to fire to a broadcast receiver. I know fine and well how to save the user's location to the db, and to compare it with the current location, etc etc.
However, given that the network location is a relatively inaccurate method for determining location, what would be a good approach for determining when the user approaches within distance X of that savedLocation.

What understand from your question is that you are tracking the user's location and saving that locations to the database. Now you want to prompt user when user reach to the previous location but there should be a specific region. If this is then you can use the below code to know the region of the user from latitude and longitude.
String latitude1, latitude2, longitude1, longitude2;
//Now Suppose you have some values in this variables.
//In your case latitude1 and longitude1 is from database and latitude2 and longitude2 is from current Location.
float radius = 500; //Distance in meters
Location location1 = new Location("GPS");
location1.setLatitude(latitude1);
location1.setLongitude(longitude1);
Location location2 = new Location("GPS");
location2.setLatitude(latitude2);
location2.setLongitude(longitude2);
Float distance = location1.distanceTo(location2);
distance = Math.abs(distance);
//Here you can compare two distances 1. distance and 2. radius
if(distance <= radius) {
//Use is in a 500 meters radius. You can notify user by notification
}

Related

Google map show toast at particular location

I want to make a small project that will allow a user to mark attendance only if he is within a particular location with tolerance of 15/20meters. I'm completely confused how to do it. It will be on a button click.
I have not written any code for the same as I don't know how to do it. I have got the api key as well as have the standard Google map fragment.
get location from google map and compare location like this
float radius = 17f;
Location newlocation = new Location("");
newlocation.setLatitude(lattitude); //lattitude is your old location
newlocation.setLongitude(longitude); // longitude is your old location
distance = myLocation.distanceTo(newlocation); //myLocation is your current location
if(distance < radius){
Toast.makeText(getApplicationContext(), "your Toast message", Toast.LENGTH_LONG).show();
}
Step 1: know your location coordinates (latitude, longitude) using Android location services
Step 2: know the "particular location" coordinates
Step 3: calculate the distance between these 2 sets of coordinates (google how to do it)
Step 4: if (distance < threshold) then { display button }

How to check the locations using LatLng values?

I'm a beginner in android and my question is regarding about google map api v2.I drew a path using my current position and my destination and I got some locations of a bus which is travelling through my path. How can I check the buse's location LatLng values are matching with my path LatLng values???
Try this,
Location crntLocation=new Location("crntlocation");
crntLocation.setLatitude(currentLatitude);
crntLocation.setLongitude(currentLongitude);
Location newLocation=new Location("newlocation");
newLocation.setLatitude(server_latitude);
newLocation.setLongitude(server_longitude);
float distance = crntLocation.distanceTo(newLocation); in meters
//distance =crntLocation.distanceTo(newLocation) / 1000; // in km
if(distance<200){
//You are within 200 meter range
}
Put this in a loop.

Android GPS accuracy in calculating distance issues

The problem I believe is well known.
So what is my problem?
I am writing an app that is using the GPS provider to find the location of the user and calculate the distance from the user to the end point. This works correctly. However a problem occurs:
The problem in details:
If you go around the city with my app it will give you some numbers for your distance but ... the distance is aways changing. No matter if I move towards my destination the distance either goes higher or goes lower (the value of the distance calculated is "jumping" around from high to low and vise versa) the the previous number of the distance but logically it should be getting lower. I believe this is because the GPS signal is sometimes lost or weak and it cant calculate the distance correctly.
What I need help with?
I want to know is there a way to filter the coordinates received from the GPS so I can get more accurate numbers for distance so when I move towards my end point the distance is calculated correctly(as possible not necessary to be 100% correct) and not go up and down the scales like crazy.
How do I get the coordinates and calculate the distance:
public void onLocationChanged(Location location)
{
txtLat = (TextView) findViewById(R.id.currentCoordinatesView);
clat = location.getLatitude();
clong = location.getLongitude();
Location location1 = new Location("Start");
location1.setLatitude(clat);
location1.setLongitude(clong);
Location locationB = new Location("Finish");
locationB.setLatitude(endLatitude); //endpoint coordinates
locationB.setLongitude(endLongitude);
distance = location1.distanceTo(locationB); //calculate the distance
TextView TextDistance = (TextView)findViewById(R.id.TextDistance);
TextDistance.setText(new DecimalFormat("##,###,###.##").format(distance)+" m");
CurLat = location.getLatitude();
CurLong = location.getLongitude();
The below answer can be further improved by saving the last, say, 10 location objects and do calculations based on those. If for instance the 10 last locations suggests that the user is moving towards the target at 1m/s, then a new location suggesting a jump of 5 meters is very likely inaccurate and should be ignored.
To filter some of the GPS updated which are way off you could simple do something like this (3 represent how accurate the position should be in respect to your actual position and may be adjusted):
public void onLocationChanged(Location location)
{
if (location.hasAccuracy() && location.getAccuracy() < 3) {
txtLat = (TextView) findViewById(R.id.currentCoordinatesView);
clat = location.getLatitude();
clong = location.getLongitude();
Location location1 = new Location("Start");
location1.setLatitude(clat);
location1.setLongitude(clong);
Location locationB = new Location("Finish");
locationB.setLatitude(endLatitude); //endpoint coordinates
locationB.setLongitude(endLongitude);
distance = location1.distanceTo(locationB); //calculate the distance
TextView TextDistance = (TextView)findViewById(R.id.TextDistance);
TextDistance.setText(new DecimalFormat("##,###,###.##").format(distance)+" m");
CurLat = location.getLatitude();
CurLong = location.getLongitude();
}
}
Here is the definition of the accuracy measure from: Location getAccuracy()
Get the estimated accuracy of this location, in meters.
We define accuracy as the radius of 68% confidence. In other words, if you draw a circle centered at this location's latitude and longitude, and with a radius equal to the accuracy, then there is a 68% probability that the true location is inside the circle.
In statistical terms, it is assumed that location errors are random with a normal distribution, so the 68% confidence circle represents one standard deviation. Note that in practice, location errors do not always follow such a simple distribution.
This accuracy estimation is only concerned with horizontal accuracy, and does not indicate the accuracy of bearing, velocity or altitude if those are included in this Location.
If this location does not have an accuracy, then 0.0 is returned. All locations generated by the LocationManager include an accuracy.

How do I stop the user waiting for a long time to get a location fix?

I am building a GPS Android application which gets the nearest places based on the user's current location.
This is what my application does:
Check if GPS or Network is available
If neither is available then don't do anything. Else, we first check for GPS if it's there, if not then we check for Network.
After using one of them, we get the current location and then send it off to the server.
Once we retrieve data from the server and update the UI, we stop listening for further location updates. Once is enough, until they press the refresh button which starts this again.
What I hope to do:
If GPS or network fails to retrieve a location, for example, 2 minutes, then we switch providers. We don't want the user to wait too long.
It would also be nice to be able to use both providers and then get the most accurate from that. I've taken a look at http://developer.android.com/guide/topics/location/strategies.html and I saw the isBetterLocation method. How would I integrate this method in my application? I'm having trouble understand how, where and when it should be called. I assume that the isBetterLocation() requires me to call both Network and GPS at the same time. It would be nice for my application to listen to both for accuracy. How do I do this? What if one of them isn't available?
Here's parts of my code:
if(!GPSEnabled && !networkEnabled)
{
Toast.makeText(this, "Error: This application requires a GPS or network connection",
Toast.LENGTH_SHORT).show();
}
else
{
if(GPSEnabled)
{
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else if(networkEnabled)
{
System.out.println("Getting updates from network provider");
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
}
This is the onLocationChanged method. I get the lat/lng values and then send them off to my server and then do appropriate stuff with it.
public void onLocationChanged(Location location)
{
//Get coordinates
double lat = (location.getLatitude());
double lng = (location.getLongitude());
Log.d("MainActivity", "got location: " + lat + ": " + lng);
//get nearest locations
new GetLocations().execute(SharedVariables.root + SharedVariables.locationsController + SharedVariables.getNearestMethod + lat + "/" + lng);
// Zoom in, animating the camera after the markers have been placed
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
System.out.println("lat = " + lat + ", lng = " + lng);
//Stop listening for updates. We only want to do this once.
locManager.removeUpdates(this);
}
Either using GPS or the network, you can't drastically reduce the eventual waiting time to get your location.
Both of these location methods have their disadvantages and advantages:
GPS usually takes a longer time to know your location, because finding and calibrating GPS satellites is a tremendous task (finding at least 3 correctly-aligned satellites is required). On top of that, add the eventual obstructing objects/environment blocking the signals. Unless you enable GPS before/when your app starts, wait is mandatory. On the other side, you get a fine-grained location.
If you only need a rough location, using the network is a solution: it returns data in a few seconds. However the precision of the location varies depending on the available/used networks; I don't have any practical examples, but I guess the precision can greatly vary. GPS will ALWAYS have a better-grained location than network.
Understand there is no predefined choice. Anything depends on what your app does with this data.
Use GPS if available, while making the location request to the network, and fall back to network if there is no GPS device. Then take either:
the first-coming result if you just need a location
the preferred result if you want the most precise data
If GPS or network fails to retrieve a location, for example, 2 minutes, then we switch providers. We don't want the user to wait too long.
In both cases, do not make a fallback timer: you'll just lengthen the waiting time in the case where the first provider fails; so do both request at the same time, unless the android API does not permit asynchronous location requests.

How to get distance between a given location and current location real time in android

I am trying to find distance between two locations in android using the LocationListener and related classes and methods.
I was able to get the coordinates of the given address by using geo coding class. And also was able to get distance between two addresses using the distanceto method.
2.Now I want to give address and get coordinates and then get the distance between previous given address location and the current location (which changes) in real time. since there is no current location method in android i got to use Location Listener.
the want the distance between the given address location coordinate and the real time changing location when moving using locationlistener and other location classes and methods. I wrote and deployed on a device with all permissions in manifest, but the gps gets disabled as soon as i start the app. Below is my code
//below code to get the address location coordinates which is succesful
int i=1;
Geocoder geo=new Geocoder(this);
List<Address> addressList = geo.getFromLocationName(adrs,i);
Address address = addressList.get(0);
if(address.hasLatitude() && address.hasLongitude()){
lat = address.getLatitude();
lon = address.getLongitude();
String adlalo= "Latitude of above address: "+lat +" " +
" "+"Longitude of above address: "+lon;
t2.setText(adlalo);
}
// and below is the location listener class
public class LoctListner implements LocationListener
{
public void onLocationChanged(Location loc)
{
t3 = (TextView) findViewById(R.id.textView3);
l1.setLatitude(lat);
l1.setLongitude(lon);
float d=l1.distanceTo(loc);
String s="the distance between starting and ending point is "+d;
t3.setText(s);
}
}
help me where i made the mistake. Unable to see the log since i got to take the device out to test.since this app needs a moving location.Thanks in advance
Unable to see the log since i got to take the device out to test.since this app needs a moving location
Perhaps you forgot to call requestLocationUpdates() ?
Unable to see the log
You have not put any Logs . Use Logs.D("YOURTAG", "Logs statements");
Location l2 = new Location("");
l2.setLatitude(loc.getLatitude());
l2.setLongitude(loc.getLongitude());
^ This is not required
float door = l1.distanceTo(loc);
You have to wait for a few minutes till the GPS Icon stops animating. This means that a fix has been attained. So check if loc is null
The Geocoder is useless.You can not get address by latlng with the Geocoder.
You can use Gson to parse a json doc from Google maps Api.The json contains your address info.

Categories

Resources