7

I am trying to determine if two locations (each with their own latitude and longitude values) are within a certain distance of each other, a 3 mile radius for example. I have double values to represent the latitude and longitude of each location.

//Location 1
Double lattitude1 = 40.7143528;
Double longitude1 = -74.0059731;

//Location 2
Double lattitude2 = 33.325;
Double longitude2 = 44.422000000000025;

I am wondering how I would determine if these two locations are within each others radius or not because I am not entirely sure how to do this with this type of value.

amelvin
  • 8,919
  • 4
  • 38
  • 59
  • 1
    I'd suggest using the [Haversine Formula](http://en.wikipedia.org/wiki/Haversine_formula). There is already an [excellent answer](https://stackoverflow.com/a/123305/98978) on here that includes a Java implementation of it. – seedhead Mar 12 '13 at 21:43

2 Answers2

7

See Great Circle distance

double CoordDistance(double latitude1, double longitude1, double latitude2, double longitude2)
{
    return 6371 * Math.acos(
        Math.sin(latitude1) * Math.sin(latitude2)
        + Math.cos(latitude1) * Math.cos(latitude2) * Math.cos(longitude2 - longitude1));
}

If your latitude and longitude are in degrees convert them to radians.

Boaz
  • 4,549
  • 2
  • 27
  • 40
0

To get the distance between two points you just need to use this snippet of code.

Point2D p1 = new Point2D(lattitude1, longitude2);
Point2D p2 = new Point2D(lattitude2, longitude2);

double distanceBetweenTwoPoints = (double)Math.sqrt((double)Math.pow((p1.x - p2.x), 2.0) + (double)Math.pow((p1.y - p2.y), 2.0));

--- EDITED ---

Please, check comments for a two coordinates (not 2D) solution.

Daniel García Baena
  • 1,191
  • 4
  • 19
  • 33
  • 2
    this gives the direct line distance between two points in 2D space. What he is looking for is the shortest distance between two points on a sphere moving on the sphere. So the Great Circle distance is what he needs. – Geoffrey Mar 12 '13 at 21:54
  • 3
    In fairness the limit on distance is 3 miles, and the curvature of the Earth over 3 miles would not be terribly significant when compared to the effects of the odd local hill in the local topology. :) – Chris Cooper Mar 12 '13 at 22:07
  • To get the distance between to coordinates he must read this post (http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates). Here there is a more complete explanation (http://www.movable-type.co.uk/scripts/latlong.html). Sorry about my other response. – Daniel García Baena Mar 12 '13 at 22:45