查找最近的区域

时间:2018-07-07 06:42:14

标签: sql-server geometry geospatial

我有一个包含地理区域的数据库,每行包含以下内容,例如:

POLYGON((-9.001111 40.624981,-9.251389 40.64887,-9.368056 40.382203,-9.4425 40.199703,-9.118056 40.14887,-9.001111 40.624981))

POLYGON((-8.75 38.216667,-8.75 38.3,-8.85 38.3,-8.85 38.216667,-8.75 38.216667))

POLYGON((-8.935001 38.909424,-9.002501 38.944424,-9.083056 38.848591,-9.015556 38.813591,-8.935001 38.909424))

我需要一个查询,该查询通过提供纬度,经度和半径来返回最接近的查询。

这是我到目前为止的结果,但是结果与预期不符:

declare
@radius int = 200,
@latitude decimal = 37.016758,
@longitude decimal = -7.930886;

DECLARE @point geography;
SET @point = geography::Point(@latitude, @longitude, 4326);

SELECT b.idFeature, a.idFeatureGeometry, a.placemark, 
c.name, c.stroke, c.stroke_opacity, c.stroke_width, c.fill, c.fill_opacity
FROM FeaturesGeometries a
inner join Features b on a.idFeature = b.idFeature
inner join FeaturesProperties c on a.idFeature = c.idFeature
WHERE @point.STIntersects([placemark].STAsText()) <> 0;

关于如何改善查询的任何想法?

1 个答案:

答案 0 :(得分:0)

我不确定您要完成什么,但是如果要找到某个点的设置半径内的所有特征,请尝试以下操作:

declare @polygons table(polygon geography);
insert @polygons values
    (geography::STGeomFromText('POLYGON ((-9.001111 40.624981, -9.251389 40.64887, -9.368056 40.382203, -9.4425 40.199703, -9.118056 40.14887, -9.001111 40.624981))', 4326)),
    (geography::STGeomFromText('POLYGON ((-8.75 38.216667, -8.75 38.3, -8.85 38.3, -8.85 38.216667, -8.75 38.216667))', 4326)),
    (geography::STGeomFromText('POLYGON ((-8.935001 38.909424, -9.002501 38.944424, -9.083056 38.848591, -9.015556 38.813591, -8.935001 38.909424))', 4326));

declare @radius float = 200 /*kilometers*/ * 1000;

declare @point geography = geography::Point(37.016758, -7.930886, 4326);

select @point , polygon, @point .STDistance(polygon) FROM @polygons where @point.STDistance(polygon) <= @radius

请记住,从STDistance返回的单位是米,而不是公里。我以为您的意思是@radius是千米(而不是米),所以我适当地调整了代码。