Search code examples
c#asp.net-mvcalgorithmiqueryablegeography

Find points withing a radius of another coordinate with IQueryable


I have users stored in a database that has latitude and longitude set on them. I want to write a filter method in my service layer.

We are using ASP.NET MVC with the repository pattern. We will use entity framework with SQLServer for now. May switch to Azure or Amazon later.

My filter method looks like this:

    public static IQueryable<IPerson> InRadius(this IQueryable<IPerson> query, Coordinate center, double radius)
    {
        return (from u in query
                where
                    (Math.Pow(u.Location.Coordinate.Latitude - center.Latitude, 2) +
                     Math.Pow(u.Location.Coordinate.Longitude - center.Longitude, 2)) < Math.Pow(radius, 2)
                select u);
    }

Looking at this, something is wrong. This is a formula for normal trigonometry. This is assuming that radius is in the same measurement as the units that the Latitude and Longitude is in.

I have a few questions on this code:

  1. Because The service layer should have no idea of the ORM, will this query be executed on the database? Will Math.Pow(double,double) be passed to the database?
  2. If It cannot be done on the database, what would be the most efficient way to filter this data. I do not want to pull down all and then sort through them in my app.
  3. Geography question: Is there a way to convert a distance (whether miles, km) into the units that Latitude and Longitude uses? This if for the radius problem.

Solution

    1. It's probably mapped to POWER but you have to try it and find out to be sure.

    2. If it doesn't translate to SQL, just change Math.Pow(someExpression, 2) to someExpression * someExpression. That will definitely be executed on the database.

    3. You can't compute distances using longitude and latitude that way. Things are different on the surface of the Earth than in the Cartesian plane.