miscalculation of distance calculation of dbgeography

I am using EF with a MSSQL DB and I am struggling with a spatial query: I am using the user location to search for restaurants ordered by distance here is the code:

DbGeography userLocation = DbGeography.FromText(userLocationWKT, 4326);
            return (from branch in DbContext.Branches
                    let distance = userLocation.Distance(branch.Location)
                    orderby distance ascending
                    where branch.Name.ToLower().Contains(searchString.ToLower()) && branch.Location != null
                    select new BranchAndDistance { Branch = branch, Distance = distance }).ToList();

the user location WKT is POINT (32.78786115814 35.0162102747709). In my test case I am sending a query that returns one restaurant with Lat=32.1300848 & Long=34.7919443 But the distance I am getting is 370237 meters which is way off.

The next image shows the QuickWatch window for the restaurant location details: Notice that in the ProviderValue text it shows POINT (34.7919443 32.1300848) as if it replaces the Lat and Long but the actual values seem OK So I conducted some more tests, since I am holding the lat and long values in separate variables I could test the following:

double? distance = Branch.Location.Distance(userLocation);
DbGeography branchLocation = DbGeography.FromText(string.Format("POINT ({0} {1})",
                                Branch.Latitude,.Branch.Longitude), 4326);
double? distance2 = branchLocation.Distance(userLocation);

The distance variable had the same incorrect distance value of 370237.85926851362 but the distance2 variabel had the correct distance value of 65061.945208184392 How can this be? I have also checked in the SQL Azure database managment and according to that the Location property (which yields an incorrect distance result) is spot on

Have I missed something? What am I doing wrong???


Your WKT for your user is not what you think it is. Specifically, that is a point that has (latitude, longitude) = (35.0162102747709, 32.78786115814). Here's a little T-SQL to show that:

DECLARE @g geography;
SELECT @g = geography::STPointFromText('POINT (32.78786115814 35.0162102747709)', 4326);

SELECT @g.Lat, @g.Long;

Need Your Help

Return first record per group

mysql ruby-on-rails ruby activerecord rails-activerecord

How can I grab an ActiveRecord::Relation object which contains records where each record is the first author for each book.

Windows script to download and print a file ... suggestions?

windows batch-file

I've need to get a file from a remote (embedded) system (which I can do either by wget or an ftp command) then print the contents of the file.