使用DbGeography和SqlGeography获得不同的答案:为什么?

时间:2017-05-30 10:14:08

标签: sql entity-framework spatial geography

我使用的是Entity Framework v6.1.3(DbGeography)和14.0.314.76(SqlGeography)。这两个都是最新版本。

DbGeography代码

        public static double GetDistance(double p1Latitude, double p1Longitude, double p2Latitude, double p2Longitude, int SRID = 4326)
    {
        System.Data.Entity.Spatial.DbGeography p1 = System.Data.Entity.Spatial.DbGeography.FromText(String.Format("POINT({0} {1} {2})", p1Latitude, p1Longitude, SRID));
        System.Data.Entity.Spatial.DbGeography p2 = System.Data.Entity.Spatial.DbGeography.FromText(String.Format("POINT({0} {1} {2})", p2Latitude, p2Longitude, SRID));
        return (double)p1.Distance(p2);
    }

SqlGeography代码

public static double GetDistance(double p1Latitude, double p1Longitude, double p2Latitude, double p2Longitude, int SRID = 4326)
    {
        SqlGeography p1 = SqlGeography.Point(p1Latitude, p1Longitude, SRID);
        SqlGeography p2 = SqlGeography.Point(p2Latitude, p2Longitude, SRID);
        return (double)p1.STDistance(p2);
    }

DbGeography给出179403.75129861536,SqlGeography给出217842.34845013986。

我已经检查过SQL Server中的计算

declare @p1 geography = geography::Point(-11.98260953020022, 54.51564130011218,4326)
declare @p2 geography = geography::Point(-10.55307433448692, 53.14334572793153,4326)
select @p1.STDistance(@p2)

答案是217842.34845014。 我还验证了Google地球专业版创建一个字符串

的距离
            <coordinates>
        54.51564130011218,-11.98260953020022,0  53.14334572793153,-10.55307433448692,0 
        </coordinates>

长度是217832。

Dbgeography调用是:

double x = EF.GetDistance(-11.98260953020022, 54.51564130011218, -10.55307433448692, 53.14334572793153);

SqlGeography调用是:

            double y = Geography.SQLServerTypes.GetDistance(-11.98260953020022, 54.51564130011218, -10.55307433448692, 53.14334572793153);

我无法理解为什么DbGeography结果如此遥远。     任何见解?     感谢。

1 个答案:

答案 0 :(得分:0)

使用“熟知文本”表示时,POINT的参数是x坐标,后跟y坐标。将此映射到地理位置时,会打破&#34;预期的&#34;约定,因为x对应于经度,y对应于纬度。

所以你需要颠倒你传递参数的顺序:

public static double GetDistance(double p1Latitude, double p1Longitude, 
                     double p2Latitude, double p2Longitude, int SRID = 4326)
{
    System.Data.Entity.Spatial.DbGeography p1 = 
     System.Data.Entity.Spatial.DbGeography.FromText(String.Format("POINT({0} {1} {2})",
          p1Longitude, p1Latitude, SRID));
    System.Data.Entity.Spatial.DbGeography p2 =
     System.Data.Entity.Spatial.DbGeography.FromText(String.Format("POINT({0} {1} {2})",
          p2Longitude, p2Latitude, SRID));
    return (double)p1.Distance(p2);
}

然后产生您的预期结果217842.34845014423。

相关问题