Spatial Linq query with distance() method
-
21-12-2019 - |
Question
I'm trying to get locations from a SQL Server database which are inside specific radius. It works fine when I use spatial data from database and pass it to the DBGeography.Distance()
method. But when i try to pass coordinates to Distance()
method like:
var sourcePoint = string.Format("POINT({0} {1})", location.lat.ToString().Replace(',','.'), location.lon.ToString().Replace(',','.'));
var origin = DbGeography.PointFromText(sourcePoint, 4326);
var result = from r in db.Locations
where r.Coordinates.Distance(origin) <= distanceMeters
select r;
It returns nothing. Although locations are inside defined radius.
Doing it like this works just fine and able to get locations inside radius:
var person = db.People.Single(p => p.PersonID == 2);
var stores = from s in db.Stores
where s.Location.Distance(person.Address) * .00062 <= 1
select new Location
{
Name = s.Name,
Latitude = s.Location.Latitude,
Longitude = s.Location.Longitude
};
I cant wrap my head around why it doesn't work in first example way. :)
Solution
It looks like you've got longitude and latitude switched in the WKT for your point. Here's a quick example to demonstrate:
DECLARE @g geography;
SET @g = geography::STPointFromText('POINT(-122.34900 47.65100)', 4326);
SELECT @g.Long, @g.Lat;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow