sirolf2009
sirolf2009

Reputation: 868

find geographic coordinates in a radius of kilometers

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.

Upvotes: 5

Views: 1672

Answers (2)

Bohemian
Bohemian

Reputation: 425003

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;
}

Upvotes: 3

AurA
AurA

Reputation: 12363

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

Upvotes: 0

Related Questions