SQL Server Geography与DbGeography

Muz*_*ain 8 .net c# sql-server entity-framework geospatial

我有两个GPS坐标,我想计算它们之间的距离,但SQL服务器上的结果与c#中的结果完全不同,我用Google搜索,发现这两种方法都以米为单位返回距离,但这种差异让我发疯.

SQL SERVER查询

select geography::Point(25.3132666, 55.2994054 ,4326)
                         .STDistance(geography::Point(25.25434, 55.32820,4326)) as Distance;
Run Code Online (Sandbox Code Playgroud)

以上sql查询的结果

Web API

String format = "POINT(25.25434 55.32820)";
                DbGeography myLocation = DbGeography.PointFromText(format, 4326);
                var users = context.Users.Select(u => new
                {
                    fullName = u.name,
                    lat = u.location.Latitude,
                    lng = u.location.Longitude,
                    distance = myLocation.Distance(u.location)
                }).ToList();
Run Code Online (Sandbox Code Playgroud)

响应

,{"fullName":"jons smith","lat":25.3132666,"lng":55.2994054,"distance":4133581.8647264037}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Hos*_*Rad 14

在定义点时,检查SQL中点的WKT表示中的纬度和经度顺序,它们如下GEOGRAPHY::POINT(Latitude, Longitude, srid):

SELECT GEOGRAPHY::Point(25.3132666,55.2994054 ,4326)
                    .STDistance(GEOGRAPHY::Point(25.25434, 55.32820,4326)) as distance;
//distance: 7142.94965953253
Run Code Online (Sandbox Code Playgroud)

但是DBGeography在使用C#代码定义时,顺序是不同的:"POINT(Longitude Latitude)"

String format = "POINT(55.32820 25.25434)";
DbGeography myLocation = DbGeography.PointFromText(format, 4326);
var users = context.Users.Select(u => new
{
    fullName = u.name,
    lat = u.location.Latitude,
    lng = u.location.Longitude,
    distance = myLocation.Distance(u.location)
}).ToList();

//distance: 7142.949659532529
Run Code Online (Sandbox Code Playgroud)

您还应该检查Users表中插入的位置.确保插入时已正确插入.否则他们将在其他地方而不是你的位置Users

更多:

SELECT GEOGRAPHY::Point(25, 55 ,4326).Lat                       //25

DbGeography.PointFromText("POINT(25  55)", 4326).Latitude.Value //55

Microsoft.SqlServer.Types.SqlGeography.STPointFromText(
            new System.Data.SqlTypes.SqlChars("POINT(25 55)"), 4326).Lat.Value;
                                                                //55
Run Code Online (Sandbox Code Playgroud)

什么是WKT,它来自哪里? 这是一个W¯¯ ell- ķ nown 牛逼不同几何类型的内线表现是由OGC在介绍简单要素访问规范和所有的软件厂商都建议遵循它在兼容性的缘故.该规范向我们展示了如何将点,线(线串),多边形和一些其他几何类型定义为文本(WKT)和二进制(WKB).

SQL Server没有完全遵循此规范,我们看到不遵循标准的结果,甚至在同一公司的不同组件中导致此类问题.