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:
Math.Pow(double,double)
be passed to the database?It's probably mapped to POWER
but you have to try it and find out to be sure.
If it doesn't translate to SQL, just change Math.Pow(someExpression, 2)
to someExpression * someExpression
. That will definitely be executed on the database.
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.