Calculating distance between two geographic locations

152,228

Solution 1

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

Look into distanceTo

Returns the approximate distance in meters between this location and the given location. Distance is defined using the WGS84 ellipsoid.

or distanceBetween

Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Distance and bearing are defined using the WGS84 ellipsoid.

You can create a Location object from a latitude and longitude:

Location locationA = new Location("point A");

locationA.setLatitude(latA);
locationA.setLongitude(lngA);

Location locationB = new Location("point B");

locationB.setLatitude(latB);
locationB.setLongitude(lngB);

float distance = locationA.distanceTo(locationB);

or

private double meterDistanceBetweenPoints(float lat_a, float lng_a, float lat_b, float lng_b) {
    float pk = (float) (180.f/Math.PI);

    float a1 = lat_a / pk;
    float a2 = lng_a / pk;
    float b1 = lat_b / pk;
    float b2 = lng_b / pk;

    double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
    double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
    double t3 = Math.sin(a1) * Math.sin(b1);
    double tt = Math.acos(t1 + t2 + t3);
   
    return 6366000 * tt;
}

Solution 2

Try This Code. here we have two longitude and latitude values and selected_location.distanceTo(near_locations) function returns the distance between those places in meters.

Location selected_location = new Location("locationA");
            selected_location.setLatitude(17.372102);
            selected_location.setLongitude(78.484196);
Location near_locations = new Location("locationB");
            near_locations.setLatitude(17.375775);
            near_locations.setLongitude(78.469218);
double distance = selected_location.distanceTo(near_locations);

here "distance" is distance between locationA & locationB (in Meters)

Solution 3

There is only one user Location, so you can iterate List of nearby places can call the distanceTo() function to get the distance, you can store in an array if you like.

From what I understand, distanceBetween() is for far away places, it's output is a WGS84 ellipsoid.

Solution 4

    private static Double _MilesToKilometers = 1.609344;
    private static Double _MilesToNautical = 0.8684;


    /// <summary>
    /// Calculates the distance between two points of latitude and longitude.
    /// Great Link - http://www.movable-type.co.uk/scripts/latlong.html
    /// </summary>
    /// <param name="coordinate1">First coordinate.</param>
    /// <param name="coordinate2">Second coordinate.</param>
    /// <param name="unitsOfLength">Sets the return value unit of length.</param>
    public static Double Distance(Coordinate coordinate1, Coordinate coordinate2, UnitsOfLength unitsOfLength)
    {

        double theta = coordinate1.getLongitude() - coordinate2.getLongitude();
        double distance = Math.sin(ToRadian(coordinate1.getLatitude())) * Math.sin(ToRadian(coordinate2.getLatitude())) +
                       Math.cos(ToRadian(coordinate1.getLatitude())) * Math.cos(ToRadian(coordinate2.getLatitude())) *
                       Math.cos(ToRadian(theta));

        distance = Math.acos(distance);
        distance = ToDegree(distance);
        distance = distance * 60 * 1.1515;

        if (unitsOfLength == UnitsOfLength.Kilometer)
            distance = distance * _MilesToKilometers;
        else if (unitsOfLength == UnitsOfLength.NauticalMiles)
            distance = distance * _MilesToNautical;

        return (distance);

    }

Solution 5

distanceTo will give you the distance in meters between the two given location ej target.distanceTo(destination).

distanceBetween give you the distance also but it will store the distance in a array of float( results[0]). the doc says If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]

hope that this helps

i've used distanceTo to get the distance from point A to B i think that is the way to go.

Share:
152,228

Related videos on Youtube

Sunny
Author by

Sunny

I love coding in Java, python, node, and. Professionally I am an App Developer. Flutter is the new &lt;3 Currently working in blockchain.

Updated on July 05, 2022

Comments

  • Sunny
    Sunny almost 2 years

    please shed some light on this situation

    Right now i have two array having latitude and longitude of nearby places and also have the user location latiude and longiude now i want to calculate the distance between user location and nearby places and want to show them in listview.

    I know that there is a method for calculating distance as

    public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results);
    

    Now what is the problem is how to pass these two array having nearby latitude and longitue in this method and get the array of distances.

    • Dinesh Sharma
      Dinesh Sharma over 12 years
      check out this link: stackoverflow.com/questions/5739734/… Hope this will help you.
    • Sunny
      Sunny over 12 years
      thanks for you reply but i want to calculate distance using above method.
    • Marmoy
      Marmoy over 12 years
      please clarify, technically you have only given us a method signature, which is not enough information to know where the method documentation can be found. Try adding information about the containing class
    • Karamsa
      Karamsa almost 9 years
      Stop using distanceTo because it retourns wrong values: stackoverflow.com/questions/30664031/…
    • CoolMind
      CoolMind almost 5 years
      @Karamsa, but in your link it is described that it works right.
    • K Pradeep Kumar Reddy
      K Pradeep Kumar Reddy over 4 years
      Is Google Distance Matrix API the right choice for calculating the distance between two geographic locations ??
  • Paresh Mayani
    Paresh Mayani almost 12 years
    can you please suggest which one provides the exact distance?
  • Harsha M V
    Harsha M V over 11 years
    Does this give the distance between two places by road ?
  • Zeeshan Chaudhry
    Zeeshan Chaudhry about 11 years
    no it returns Displacement (The Shortest Distance Between Two Points)
  • snachmsm
    snachmsm over 8 years
    float pk = (float) (180/3.14169); - small misspell, this is not Pi... it should be 3.14159 or Math.PI used (also Math class instead deprecated FloatMath). 57 upvotes and no one noticed? :D
  • Secret Squirrel
    Secret Squirrel about 8 years
    Anyone confirm whether locationA.distanceTo(locationB) takes the altitude into consideration?
  • spaaarky21
    spaaarky21 about 8 years
    What's the second code block for? Why wouldn't you just use Location. distanceBetween()?
  • Mike H
    Mike H about 7 years
    Secret Squirrel: locationA.distanceTo(locationB) will ignore altitude, even when set using setAltitude(<meters>). See: stackoverflow.com/questions/38149168/…
  • Arnold Brown
    Arnold Brown almost 5 years
    @Karthi is the first block return a distance in Meters?
  • K Pradeep Kumar Reddy
    K Pradeep Kumar Reddy over 4 years
    What is difference between calculating distance using Google Distance Matrix Api versus calculating using the above code ??
  • luke cross
    luke cross almost 4 years
    This returns in Km or Miles?