TSQL 地理空间数据多边形 Lat/Long 搜索

TSQL Geography Spatial Data Polygon Lat/Long Search

TSQL SQL 服务器 2008 r2

是否可以存储由纬度和经度组成的多边形,然后在该多边形中执行搜索以查看给定的 Latitude/Longitude 是否存在于该多边形中?

如果是这样,该如何处理?

如果没有,有人可以提供有关解决此问题的最佳方法的建议吗?

示例多边形

LatLng(55.297622963050465, -4.627166781574488),
LatLng(55.25851203752759, -3.5724792815744877),
LatLng(55.034056344339206, -3.5450134612619877),
LatLng(54.955277168321636, -3.7647400237619877),
LatLng(54.92372217917785, -4.113555941730738),
LatLng(54.96946883538248, -4.561248812824488),
LatLng(55.151935308382306, -4.712310824543238);

Lat/Long 搜索

LatLng(55.10029008969451, -4.100017953449488),

提前致谢

简而言之,是的,这是可能的。我建议您从以下 MSDN link 开始,然后从那里做一些研究:

Working with Spatial Data

具体来说,请注意以下可用于获取答案的方法:

  • STWithin()
  • STIntersects()

请注意,对于 SQL 2008 R2,您只能使用不大于一个半球的多边形。如果您需要支持更大的对象,我会考虑 SQL 2012 或更高版本。

基本示例:

declare @g geography = Geography::STPolyFromText("<WKT Polygon Text>, 4326); -- 4326 is a common SRID
declare @p point = Geography::STPointFromText("<WKT Point Text>, 4326); -- SRID MUST match polygon

select @p.STWithin(@g); -- 1 is true, 0 is false

多亏了@Jon Bellamy,我才能够找到这个解决方案

Ed's Spatial Blog 到 "fix" 多边形环方向问题的帮助下

IF OBJECT_ID ( 'dbo.SpatialTable', 'U' ) IS NOT NULL 
    DROP TABLE dbo.SpatialTable;
GO

CREATE TABLE SpatialTable 
    ( id INT IDENTITY (1,1),
    GeogCol1 GEOGRAPHY, 
    GeogCol2 AS GeogCol1.STAsText() );
GO

DECLARE @geom GEOMETRY = 'POLYGON(( 55.297622963050465 -4.627166781574488,
                                    55.25851203752759 -3.5724792815744877,
                                    55.034056344339206 -3.5450134612619877,
                                    54.955277168321636 -3.7647400237619877,
                                    54.92372217917785 -4.113555941730738,
                                    54.96946883538248 -4.561248812824488,
                                    55.151935308382306 -4.712310824543238,
                                    55.297622963050465 -4.627166781574488))';

DECLARE @geog GEOGRAPHY = @geom.MakeValid().STUnion(@geom.STStartPoint()).STAsText()

INSERT INTO SpatialTable (GeogCol1) VALUES (@geog)

DECLARE @g GEOGRAPHY 
SET @g = (SELECT GEOGRAPHY::STPolyFromText(GeogCol2, 4326) FROM dbo.SpatialTable); -- 4326 is a common SRID

DECLARE @p GEOGRAPHY
SET @p = GEOGRAPHY::STPointFromText('POINT(55.10029008969451 -4.100017953449488)', 4326); -- SRID MUST match polygon

SELECT @p.STIntersects(@g); -- 1 is true, 0 is false

IF OBJECT_ID ( 'dbo.SpatialTable', 'U' ) IS NOT NULL 
    DROP TABLE dbo.SpatialTable;
GO