I am using LocationManager to get the values of Latitude and Longitude of a user. These values are updated regularly to a database.
Now, i want to find out the distance between two users basing on the stored Latitude and Longitude values. I want to display a message when distance between two users is less than (say 100 meters). Can anyone please guide me with a tutorial or some sample code of how to achieve it.
You can have a look at the Location class. You can set the longitude and latitude and there is a distanceTo method that you can use
Ou pode utilizar este metodo que eu desenvolvi...
Or you can use this method I developed...
public static Double distance(latitudeA, latitudeB, longitudeA, longitudeB) {
double radius = 3958.75;
double dlat = ToRadians(Double.parseDouble(String.valueOf(latitudeB))
- Double.parseDouble(String.valueOf(latitudeA)));
double dlon = ToRadians(Double.parseDouble(String.valueOf(longitudeB))
- Double.parseDouble(String.valueOf(longitudeA)));
double a = Math.sin(dlat / 2)
* Math.sin(dlat / 2)
+ Math.cos(ToRadians(Double.parseDouble(String.valueOf(latitudeA))))
* Math.cos(ToRadians(Double.parseDouble(String.valueOf(latitudeB)))) * Math.sin(dlon / 2)
* Math.sin(dlon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
Double d = radius * c;
double meterConversion = 1609.00;
return d * meterConversion;
}
private static double ToRadians(double degrees) {
double radians = degrees * 3.1415926535897932385 / 180;
return radians;
}
Related
I want to create an app in which I want to show how much distance does the user has been traveled.
I have tried using float distance = locationA.distanceTo(locationB); but it just draws a simple straight line from start to end and then calculates the distance.
I want to calculate the traveled distance based on the traveled route. Is it possible to do so using any Google maps API?
you just need service to continuously observer that user change it's location then you can use these function to calculate the distance.
public double GetDistanceInKm(double lat1, double lon1, double lat2, double lon2)
{
final int R = 6371;
// Radius of the earth in km
double dLat = deg2rad(lat2 - lat1);
// deg2rad below
double dLon = deg2rad(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = R * c;
// Distance in km
return d;
}
private double deg2rad(double deg)
{
return deg * (Math.PI / 180);
}
Assuming you have a bunch of lat long points making up a route. You have to take the distance from the previous point to the next point for all points and keep a total of that. In other words you need a-lot of lat lon data in between the route or you are just going to get a straight line.
You can use google maps api to get the distance
use this link to understand how to use it.
In an Android application I am struck in a problem any one have information about GPS coordinates from map , please help.
The problem is if I have coordinates(latitude and longitude) of two different points on Map and
I want to check that the points are on the same location on map
Secondly are the two points are nearer to each other according to any criteria
For example .. if the point is in the 100m radius of the other point it seems to be nearer.
You can use haversine formula to calculate two points,
public static void main(String[] args) {
// TODO Auto-generated method stub
final int R = 6371; // Radious of the earth
Double lat1 = Double.parseDouble(args[0]);
Double lon1 = Double.parseDouble(args[1]);
Double lat2 = Double.parseDouble(args[2]);
Double lon2 = Double.parseDouble(args[3]);
Double latDistance = toRad(lat2-lat1);
Double lonDistance = toRad(lon2-lon1);
Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
Double distance = R * c;
System.out.println("The distance between two lat and long is::" + distance);
}
You can compare this distance.This will do your job.
I have a list of latitude and longitude stored in database. Now I'm trying to develop a function on finding nearby place from my current location. Means that, i have to search all the latitude and longitude from my database and see which of the places are within my area will be shown.
Location.distanceBetween(lat1,lon1, lat2,lon2, result);
To find the distance from one two-dimensional point to another you can use the Haversine formula, (without calling any API functions.)
// All measurements are in meters
var rad = function(x) {
return x * Math.PI / 180;
};
var getDistance = function(coord1, coord2) {
// This is the Earth's radius
var earthRad = 6378137;
var dLat = rad(coord2.lat() - coord1.lat());
var dLong = rad(coord2.lng() - coord1.lng());
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(coord1.lat())) * Math.cos(rad(coord2.lat())) *
Math.sin(dLong / 2) * Math.sin(dLong / 2);
var b = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var distance = earthRad * b;
// Returns distance from coord1 to coord2 in meters
return distance;
};
Your question is a bit broad so this might not be the best solution. If you were constantly updating your current location you'd have to implement a Tree Sorting algorithm or some other way of optimizing performance rather than checking through your database for distances on every update.
You can use the Location object. The distanceBetween or distanceTo method will give you the 'as the crow flies' distance between two points. From there you can filter your results and display only the places you want to.
here is what i use
public void nearBy() {
if (map.getMyLocation() != null) {//check if my location was found
db = new MyDatabase(MainActivity.context);
Cursor medecin = db.lireMedecin();//read values from database
map.clear();//clearing the map
while (medecin.getPosition() < medecin.getCount()) { //cheking if this doctor is nearby...
String Lat1 = medecin.getString(5);//doctor's latitude
String Lon1 = medecin.getString(6);//doctor's longitude
LatLng me = new LatLng(map.getMyLocation().getLatitude(), map.getMyLocation().getLongitude());//my location
LatLng med = new LatLng(Double.parseDouble(Lat1), Double.parseDouble(Lon1));//doctor location
if (CalDist(me, med) < 6) {//if distance is < 6km add marker to the map
map.addMarker(new MarkerOptions().position(med).title(medecin.getString(1) + " " + medecin.getString(2))
.snippet(medecin.getString(4)).icon(BitmapDescriptorFactory
.fromResource(Icone(medecin.getString(7).charAt(0))))); //showing the doctor on the map
}
medecin.moveToNext();//next doctor
}
} else
Toast.makeText(context, "Gps signal not valid", Toast.LENGTH_SHORT).show();//can't find my position
}
calculate distance :
public static double CalDist(LatLng StartP, LatLng EndP) {
int Radius = 6371;//radius of earth in Km
double lat1 = StartP.latitude ;
double lat2 = EndP.latitude ;
double lon1 = StartP.longitude ;
double lon2 = EndP.longitude ;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
return Radius * c;
}
I have used tutorial from the link below to display Google map route in Android app. My question is how can I calculate distance to polyline points on map? Like when I use Google maps app and it tells when a street turn is getting close. I want to implement similar feature in my app. I am able to display the route polyline on the map and it updates itself while I drive along it but I want it to warn me 500 feet in advance of a coming turn. How can I do that?
Here is the link:
http://jigarlikes.wordpress.com/2013/04/26/driving-distance-and-travel-time-duration-between-two-locations-in-google-map-android-api-v2/
I use this method for Markers. Assuming you have Latitude and Longitude of the points that make up the Polyline this should do:
public class MapUtils {
public static float distBetween(LatLng pos1, LatLng pos2) {
return distBetween(pos1.latitude, pos1.longitude, pos2.latitude,
pos2.longitude);
}
/** distance in meters **/
public static float distBetween(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
* Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;
int meterConversion = 1609;
return (float) (dist * meterConversion);
}
}
To determine wether the road is turning, I would look into euclidean angle between vectors (x being current location and y being a polyline point)
Simply take your current location and a LatLng from some distance ahead for this.
Calculation is based on: http://en.wikipedia.org/wiki/Euclidean_space#Angle
Location currentLocation; // obtained somewhere in your code
LatLng polylinePoint; // a point further ahead
double cLat = currentLocation.getLatitude();
double cLon = currentLocation.getLongitude();
double pLat = polylinePoint.latitude;
double pLon = polylinePoint.longitude;
double angle = Math.acos(
(cLat*pLat+cLon+pLon) / norm(cLat,cLon)*norm(pLat,cLon));
private double norm(double x, double y) {
return Math.sqrt(Math.pow(x, 2)*Math.pow(y, 2));
}
This is untested so might contain error.
I am developing an application in which I need to calculate the distance travelled. I am facing a problem while calculating the distance.
Here is my code:
locationmanager.requestLocationUpdates(bestProvider,0,0,new Listener());
public class Listener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
if(location!=null) {
if(loc1==null) {
loc1=new Location(location);
}
speed=location.getSpeed()*3.6;
loc2=new Location(location);
dist+=loc1.distanceTo(loc2);
loc1=loc2;
breaktv.setText(""+dist/1000);
My intention is calculate the total distance travelled by car or something. But distanceTo() method is not working well for me.
Technically it should work.
I have some suggestions :
dist must be float (if it isn't already)
dist += loc2.distanceTo(location), there is no need to create loc1
This is the code I've used
if(lastLoc != null)
{
ttf = (location.getTime() - lastLoc.getTime()) / 1000;
int R = 6371;
double lat1 = Math.PI / 180.0 *lastLoc.getLatitude();
double lon1 = Math.PI / 180.0 *lastLoc.getLongitude();
double lat2 = Math.PI / 180.0 *location.getLatitude();
double lon2 = Math.PI / 180.0 *location.getLongitude();
// double dLon = Math.PI / 180.0 * (location.getLongitude() - lastLoc.getLongitude());
double dLat = (lat2-lat1);
double dLon = (lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c;
totalDistance += d;
}
lastLoc = location;
Here is another Question on SO where I have posted 2 Answers one for the User Defined function to get the distance and other to User android.Location class method to calculate it.
Hope this will help you.
When You start your jurney take the CurrentLocation and store it may be using SharedPreferences,
Then I think you need to Continuosly keep updating the Distance Travelled,
You just use OnLocationChanged same way and Call the method above two mentioned from there to know the Current Distance Travelled.
EDIT:
here is a good example that may help you,Link To OpenSource Project