将地理转换为几何SQL Server 2008R2

时间:2013-04-24 19:39:22

标签: sql geometry spatial geography

  

您好,我在SQL Server中有以下代码,如果我想,为什么   计算@geog的sTArea失败并且@geom成功了吗?我怎么能   将此多边形从几何转换为地理数据类型以获取   STArea ?,谢谢。

DECLARE @geom geometry;
SET @geom = geometry::STGeomFromText('POLYGON ((-99.213546752929688 19.448402404785156, -99.2157974243164 19.449802398681641, -99.2127456665039 19.450002670288086, -99.213546752929688 19.448402404785156))', 4326); 
select @geom.STArea();

DECLARE @geog geography;
SET @geog = geography::STGeomFromText('POLYGON ((-99.213546752929688 19.448402404785156, -99.2157974243164 19.449802398681641, -99.2127456665039 19.450002670288086, -99.213546752929688 19.448402404785156))', 4326); 
select @geog.STArea();

1 个答案:

答案 0 :(得分:9)

我捅了一下,这个答案How can I convert Geometry data into a Geography data in MS SQL Server 2008?或多或少仅指向http://blogs.msdn.com/b/edkatibah/archive/2008/08/19/working-with-invalid-data-and-the-sql-server-2008-geography-data-type-part-1b.aspx,这使我得到了合理的解释和工作代码。

关键点:您必须首先确保您的几何图形可以转换为有效的地理位置。

代码(当然可以将一些操作组合在一起,但为了清楚起见,它们在这里被分解。)

DECLARE @geog GEOGRAPHY;
DECLARE @geom GEOMETRY;

SET @geom = GEOMETRY::STGeomFromText('POLYGON ((-99.213546752929688 19.448402404785156, -99.2157974243164 19.449802398681641, -99.2127456665039 19.450002670288086, -99.213546752929688 19.448402404785156))', 4326); 
SET @geom = @geom.MakeValid() --Force to valid geometry
SET @geom = @geom.STUnion(@geom.STStartPoint()); --Forces the correct the geometry ring orientation
SET @geog = GEOGRAPHY::STGeomFromText(@geom.STAsText(),4326) 

SELECT @geog.STArea();

对于那些不会一直阅读Spatial Ed的博客的人发表的一篇重要提示,“请记住,这种方法很天真,因为它不能适应几种潜在的边缘条件。从不如此,在许多情况下,这种方法应该有效。“