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) +
开发者_JAVA技巧 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:
- 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? - 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.
- 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.
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)
tosomeExpression * 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.
Math.Pow
should be mapped by the entity framework to the appropiate method in sql.- if 1. shouldn't be true, just calculate the power yourself by multiplication, which will be executed in the database
- I don't have sufficient knowledge to answer that question, but if I remember correctly, this will be quite hard due to the shape of the earth (depending on the reference frame and the actual distance).
精彩评论