How to Compare saved (in database ) Geo Location(Longitude and Latitude) with currently getting one using GPS.i tried following link but it doesn't work for me ,getting wrong output.Please help me i am new in Android.
How to use coarse location to compare with saved location in database
my requirement is exact as explained in ANS.
i did
float radius = 150; // distance in meter
double latitude_new= gps.getLatitude();
double longitude_new = gps.getLongitude();
Location location1= new Location("gpslocation");
location1.setLatitude(21.xxxxxxx);
location1.setLongitude(78.xxxxxxx);
Location location2= new Location("gpslocation");
location2.setLatitude(latitude_new);
location2.setLongitude(latitude_new);
float distance = location2.distanceTo(location1);
distance=Math.abs(distance);
//comparing two distance and radius
if (distance <= radius){
Toast.makeText(MyActivity.this, "At home", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MyActivity.this,"Not in Home",Toast.LENGTH_SHORT).show();
}
problem is i m getting only "Not in Home" at SAME location which i have hard-coded and even on other locations(other than hard-coded).
thanks
You have provide latitude for the longitude also , edit your code as follows and try ,
location2.setLongitude(longitude_new);
Related
In my Android application i need to get the traveled road with car and i check it with google android directions API and GPS.
But the problem is that some times the GPS location is not precise and i can get an error of 10Km for some lecture and that means that in a total travel of 150km my "distance traveled" can be 250km and it's wrong!
Yesterday i test it in highway and the problem is that when the marker is located out from highway, the calculation of distance traveled from my current position and the last marker located by road is very wrong (in this case out of the highway).
There is some best way for getting traveled distance with car using the phone?
Maybe some better code for getting more precise GPS position?
Here is my code:
private void getUserLocation() {
Log.d(TAG, "getUserLocation()");
checkLocationPermission();
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
String stringStartLat, stringStartLng;
double lat = location.getLatitude();
double lng = location.getLongitude();
//Start position of device
if (travelInfo.getStartLat() == 0 && travelInfo.getStartLng() == 0) {
travelInfo.setStartLat(lat);
travelInfo.setStartLng(lng);
//Set lastcoordinates equals to start
travelInfo.setLastLat(lat);
travelInfo.setLastLng(lng);
}
//Current position of device
travelInfo.setCurrentLat(lat);
travelInfo.setCurrentLng(lng);
stringStartLat = Double.toString(travelInfo.getStartLat());
stringStartLng = Double.toString(travelInfo.getStartLng());
//Set the TextView in the fragment with start coordinates
Log.d(TAG,"LatitudeStart: " + stringStartLat);
Log.d(TAG,"LongitudeStart: " + stringStartLng);
if (startMarker == null) {
//Add the user location to the map with a marker
LatLng userLoction = new LatLng(travelInfo.getStartLat(), travelInfo.getStartLng());
startMarker = googleMap.addMarker(new MarkerOptions()
.position(userLoction)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
.title("Start Position")
.snippet("Show the start position of user"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(userLoction).zoom(9).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else {
LatLng currentLocation = new LatLng(travelInfo.getCurrentLat(), travelInfo.getCurrentLng());
currentPositionMarker = googleMap.addMarker(new MarkerOptions()
.position(currentLocation)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
.title("Current Position")
.snippet("Show the current position of user during travel"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(currentLocation).zoom(11).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
if (travelInfo.getEndLat() != 0 && travelInfo.getEndLng() != 0) {
Log.i(TAG, "Dentro if userlocation");
//Get total distance of travel
getTotalDistanceTime(travelInfo);
//Get the percurred distance from last known coordinates
getPercurredDistance(travelInfo);
}
}
}
});
}
And getpercurredDistance use google direction API with this url
String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + obj.getLastLat() + "," + obj.getLastLng() + "&destination=" + obj.getCurrentLat() + "," + obj.getCurrentLng() + "&mode=driving&key=AI*******************I";
For getting distance traveled from last marker and current position marker.
But some times it put the localized position too far from real position... how avoid this?
EDIT
The method that i use is good for my work? mFusedLocationClient.getLastLocation()
There is no possibilities to get more precise GPS position from GPS sensor of android device, but you can filter "wrong" points this ways:
1) for each travel point get several values of Lat and Lng, discard the minimum and maximum and average the remaining ones;
2) log timestamps of each travel point and compare it for two neighboring points: speed (distance between that two points divided by time interval of that points) grater than max. car speed (e.g. 250 km/h) that means the second point is wrong (if first point is good of course).
3) use Google Maps Roads API to find best-fit road geometry for a given set of GPS coordinates.
Also take a look at this question.
For real-time location purposes, location updates allow you to request location updates at different intervals. See the android developer location documentation. The function you want is FusedLocationProviderClient.requestLocationUpdates.
There is no reason GPS (or any other widely used location technology) should ever give you 10km error for a single location estimate. If you are getting this, there is a large mismatch between when you the location estimate was made and when you are requesting it.
i am trying to work on application , in which i have List of location from database and i want to check Which location from database is near to my current location within few miles like 20 miles and list got refreshed automatically with the refined Location and then send notification to user that you have enter to this location...
I have searched over this and come to know about Geofencing But i did not get it properly.. so please suggest me how should i start working on it ... Any sample , code or link will be helpful
thanks in advance
I have used one function distanceTo to calculate distance between to Locations.
I have coded it for only 100 mtr, you need to change value of distance you want to compare with.
private boolean isMarkerIn100(ArrayList<Model> arrayList) {
Location locationA = new Location("LocationA");
locationA.setLatitude(latitude);
locationA.setLongitude(longitude);
for (int i = 0; i < arrayList.size(); i++) {
Location locationB = new Location("LocationB");
locationB.setLatitude(arrayList.get(i).getLat());
locationB.setLongitude(arrayList.get(i).getLng());
if (locationA.distanceTo(locationB) < 100 && arrayList.get(i).getHit() > 4) {
return false;
}
}
return true;
}
In above code, latitude and longitude are for my (User's) location (Say locationA) and ArrayList is data from database with lat and lng.
I'm wrinting a application and I have to show the distance covered while I'm running.
I use the function "public void onLocationChanged" of the LocationListener. When the user tap a botton and start running I want to show the distance he covered updated to the point in which he is located.
I've written this code:
public void onLocationChanged(Location location) {
if(location != null) {
if(location.hasSpeed()){
if(latitude1 == 0 && longitude1 == 0){
latitude1 = (location.getLatitude()*Math.PI)/180;
longitude1 = (location.getLongitude()*Math.PI)/180;
} else{
latitude2 = (location.getLatitude()*Math.PI)/180;
longitude2 = (location.getLongitude()*Math.PI)/180;
distance = (6372.795477598)*Math.acos(Math.sin(latitude1)
*Math.sin(latitude2)+Math.cos(latitude1)
*Math.cos(latitude2)*Math.cos(longitude1-longitude2));
sumDistance += distance;
latitude1 = latitude2;
longitude1 = longitude2;
}
tv.setText("Distance covered=" + sumDistance + " m");
}
}
}
Is it accurated?
Just a Suggestion:
Store the Latitude and Longitude of the start location and the end location when the user clicks the appropriate button.
and then you could use distanceBetween or distanceTo to get the distance between those two geoPoints.
P.S: This may not work if the user will start and end his run at the same point ;)
Addition:
Check this tutorial:
Recently google has improved its location based API's. They have fused the sensors with the location based api's to share examples of how location can be made more accurate (about 4 times more effective) and consume much lesser power (10 times lesser).
Some interesting links for you to go through will be this and video google io.
SO link for how to use the API's here
I'm starting to create an application which will be show notification, when user will be within radius 1 km from my shop.
I have xml file, which show my shop lat and log:
<SHOPS>
<SHOP LON="19.456865000000000000" LAT="51.765639000000000000" CITY="90-423 Łódź" STR="ul. Piotrkowska 95" PHOTO=""/>
<SHOP LON="18.564883000000000000" LAT="54.443416000000000000" CITY="81-759 Sopot" STR="ul. Bohaterów Monte Casino 26" PHOTO=""/>
<SHOP LON="19.455248000000000000" LAT="51.770487000000000000" CITY="90-125 Łódź" STR="ul. Narutowicza 41" PHOTO=""/>
<SHOP LON="20.930370000000000000" LAT="52.241939000000000000" CITY="01-460 Warszawa" STR="ul. Górczewska 124" PHOTO=""/>
</SHOPS>
How can I do that, how to designate a radius of lat and long?
If you want to find the distance between two diferent locations (i.e. the user location and one of your shps location) you can use the following code:
Location shopLoc = new Location("");
shopLoc.setLatitude(shopLat); //get this value from your xml file
shopLoc.setLongitude(shopLon); //get this value from your xml file
Location userLoc = new Location("");
userLoc.setLatitude(userLat); //get this value from gps or other position device
userLoc.setLongitude(userLat); //get this value from gps or other position device
//Finaly get the distance with
float distance = userLoc.distanceTo(shopLocation)
Now you can compare the distance with 1 Km and show the notification
This is maybe a noob question but im not 100% sure about it.
How can i make a Location Object using Geo points? I want to use it to get the distance between two points.
I already found a thread where it says
Location loc1 = new Location("Location");
loc.setLatitude(geoPoint.getLatitudeE6);
loc.setLongitude(geoPoint.getLongitudeE6);
Location loc2 = new Location("Location2");
loc2.setLatitude(geoPoint.getLatitudeE6);
loc2.setLongitude(geoPoint.getLongitudeE6);
and then i would use the distanceTo() to get the distance between the two points.
My Questions
What is the Providername for? ...new Location("What is this here???")
So do i have to define a Provider before or something?
I want to use this code in a for() to calaculate between more GeoPoints.
And btw - i have to convert the E6 Values back to normal?
Not exactly
loc.setLatitude() takes a double latitude. So the correct code is:
loc.setLatitude( geoPoint.getLatitudeE6() / 1E6);
Location() constructor take the name of the GPS provider used. It can be LocationManager.GPS_PROVIDER or NETWORK_PROVIDER among other values
To get the distance between two point you can use the Location class and more precisely the distanceBetween static method.
The doc is quite clear on what it does but here a quick code sample:
float[] results = new float[3];
Location.distanceBetween(destLatitude, destLongitude, mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(), results);
// result in meters, convert it in km
String distance = String.valueOf(Math.round(results[0] / 1000)) + " km");
To convert from minute/second to degree you can use the convert method of the Location class.
Log.i("MapView", "Map distance to mark (in meters): " + myLocation.distanceTo(GeoToLocation(point)) + "m");
then
public Location GeoToLocation(GeoPoint gp) {
Location location = new Location("dummyProvider");
location.setLatitude(gp.getLatitudeE6()/1E6);
location.setLongitude(gp.getLongitudeE6()/1E6);
return location;
}