5

I have a dataset of around 300.000 vectors, randomly placed around the earth using lattitude and longitude. Say that I'm at 51.9167° N, 4.5000° E, how do I find all vectors around me in a radius of, for example, 100km? Plain math is preferred. Java and pseudo code are fine too.

sirolf2009
  • 819
  • 8
  • 15
  • Here's a [java implementation](http://stackoverflow.com/a/7427290/256196) of the [haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) – Bohemian Oct 01 '15 at 07:47
  • You can use the [Haversine formula](https://en.wikipedia.org/wiki/Haversine_formula) to calculate the distance between latitude and longitude. – Rahul Tripathi Oct 01 '15 at 07:46
  • This has been asked before, here are a few answers to get you started: - [Plain math explanation](http://gis.stackexchange.com/questions/2951/algorithm-for-offsetting-a-latitude-longitude-by-some-amount-of-meters "Plain math explanation") - [C# code sample](http://stackoverflow.com/questions/3269202/latitude-and-longitude-bounding-box-for-c) - [Python code sample](http://stackoverflow.com/questions/238260/how-to-calculate-the-bounding-box-for-a-given-lat-lng-location) – Addys Oct 01 '15 at 07:45
  • When you say "dataset", do you mean a list/set? something else? – Bohemian Oct 01 '15 at 07:49
  • You can also refer this: http://www.movable-type.co.uk/scripts/latlong.html – Rahul Tripathi Oct 01 '15 at 07:54

2 Answers2

3

Assuming you have a Location class with lat/long and a Collection<Location> you want to process, you can do it like this:

Collection<Location> locations; // filled somewhere
final Location here;

List<Location> within100km = locations.stream()
    .filter(l -> haversine(l.getLatitude(), l.getLongitude(),
      here.getLatitude(), here.getLongitude()) <= 100)
    .collect(Collectors.toList());

public static double haversine(
        double lat1, double lng1, double lat2, double lng2) {
    int r = 6371; // average radius of the earth in km
    double dLat = Math.toRadians(lat2 - lat1);
    double dLon = 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(dLon / 2) * Math.sin(dLon / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = r * c;
    return d;
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

Found some equation that does the same

From latitude/longitude to n-vector

The n-vector for a point φ,λ on the earth’s surface, where latitude = φ and longitude = λ, is defined as

             cosφ·cosλ   
v{x,y,z} =   cosφ·sinλ   
             sinφ   

Refer this page

AurA
  • 12,135
  • 7
  • 46
  • 63