Source code to find the distance between two geo points

6.5k Views Asked by At

I'm working on an Android app and I want to add store locator details and map view.I searched a lot.,but I'm n't getting anything purposeful.I'm tensed and strongly need your help.

The problem is,I want to find the distance between 2 co-ordinates,I got one Haversine formula.,but don't know how to run the program successfully.,As I'm a beginner in Android,please help to do the coding in stepwise.,ie the xml code also..,please.,please.,

3

There are 3 best solutions below

0
On

http://developer.android.com/reference/android/location/Location.html

Look into distanceTo or distanceBetween. You can create a Location object from a latitude and longitude:

Location location = new Location("");
location.setLatitude(lat);
location.setLongitude(lon);
0
On

Use this code. you will get distance between two geo points.

 private String distance(double lati, double longi, double curlati1,
        double curlongi1) {

    double theta = longi - curlongi1;
    double dist = Math.sin(deg2rad(lati)) * Math.sin(deg2rad(curlati1))
            + Math.cos(deg2rad(lati)) * Math.cos(deg2rad(curlati1))
            * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 60 * 1.1515;

    dist = dist * 1.609344;

    result = Double.toString(dist);
    System.out.println("dist_result :" + result);
    return (result);
}

/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts decimal degrees to radians : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}

/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts radians to decimal degrees : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
}
0
On

From MotoDev snippets (Distance between GPS Coordinates):

Location originLocation = new Location("gps");
Location destinationLocation = new Location("gps");
originLocation.setLatitude(originLatitude);
originLocation.setLongitude(originLongitude);
destinationLocation.setLatitude(originLatitude);
destinationLocation.setLongitude(originLongitude);
float distance = originLocation.distanceTo(destinationLocation);