Damir Shaykxutd
Damir Shaykxutd

Reputation: 29

How do I find 10 elements by longitude and latitude in 1 km radius using LINQ?

In my case on picture firstPoint0 - as example my first point and center of the circle, relative this point confine screenings by radius 1 km. I need to show just all points in my radius, others points thisPoint not show by linq query.

var flats = context.Flats;
var first = flats.FirstOrDefault(x => x.Lattitude && x.Longitude);         
var getAllInRadius = flats.Where(? take points where distance <= 1 km)

Example on picture

Upvotes: 1

Views: 896

Answers (1)

ken2k
ken2k

Reputation: 48975

Just use the Haversine formula that returns the great-circle distance between two points on a sphere:

// Returns the great circle distance between two flats, as meters
public static double DistanceBetweenFlats(Flat flat1, Flat flat2)
{
    const int EarthRadius = 6371;
    double latitude = ToRadian(flat2.Latitude - flat1.Latitude);
    double longitude = ToRadian(flat2.Longitude - flat1.Longitude);
    double tmp = (Math.Sin(latitude / 2) * Math.Sin(latitude / 2)) +
        (Math.Cos(ToRadian(flat1.Latitude)) * Math.Cos(ToRadian(flat2.Latitude)) *
        Math.Sin(longitude / 2) * Math.Sin(longitude / 2));
    double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(tmp)));
    double d = EarthRadius * c;
    return d * 1000;
}

...

var centerFlat = ...;
var getAllInRadius = flats.Where(z => DistanceBetweenFlats(centerFlat, z) <= 1000);

Of course all of this assumes you're using LINQ in memory (not LINQ to Entities). If it's not the case, you'll have to use spatial queries.

Upvotes: 1

Related Questions