开发者

SQL Server Geo-spacial Data & C# - One of these are WRONG!

So this questions has few parts to it, but hopefully someone will have enough knowledge to help.

In my SQL Server Database I have 2 Location records with the following properties latitude(nL开发者_如何学Pythonatitude), longitude(nlongtitue) & geography(gGeoLocation) values in that order.

Record 1: 39.283638, -76.568567, 0xE6100000010C91F3FE3F4EA443406EA5D766632453C0

Record 2: 39.285200, -76.554366, 0xE6100000010CDC68006F81A44340EB0088BB7A2353C0

I created the Geography values by using the SQL query below:

UPDATE [Location] SET gGeoLocation = geography::STPointFromText('POINT(' + CAST(nlongtitue AS VARCHAR(20)) + ' ' + CAST([nLatitude] AS VARCHAR(20)) + ')', 4326)

Now lets say I want to search my Location table to determine which of those locations are with in a certain radius of certain latitude/longitude (39.290555,-76.609604) I was using the following query:

SELECT * FROM [Location] WHERE gGeoLocation.STDistance(geography::Point(@Latitude, @Longitude, 4326)) < ((@Miles * 1000) * 0.621371192)

Then I was checking my results against a C# function and two results are not the same, so one of these has to be wrong or I am missing something. Here is the C# function:

//calculate haversine distance for linear distance - Miles
public static double haversine_mi(double lat1, double long1, double lat2, double long2)
{
    double dlong = (long2 - long1) * d2r;
    double dlat = (lat2 - lat1) * d2r;
    double a = Math.Pow(Math.Sin(dlat / 2.0), 2) + Math.Cos(lat1 * d2r) * Math.Cos(lat2 * d2r) * Math.Pow(Math.Sin(dlong / 2.0), 2);
    double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
    double d = 3956 * c;

    return d;
}

Ultimately if some could provide me a SQL query that would search the location table within a certain radius and also return the distance between the location and the search point in miles and in km that would awesome.

But also I would like to understand why I am getting different results in what should return the same. I am pretty new to geo-spacial data.


You're using GEOGRAPHY which is calculations on the surface of a sphere. You might want to use GEOMETRY which is calculations on a plane. It makes a difference. Also, check your SRIDs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜