假设我有一个城市的纬度和经度,我需要找到距离这个地方不到100英里的所有机场。我怎么做到这一点?我的数据驻留在SQL Server中。 1个表格包含lat和long的所有城市信息,另一个包含lat和long的机场信息。
答案 0 :(得分:4)
首先......转换城市的数据点
DECLARE @point geography;
SELECT geography::STPointFromText('POINT(' + CAST(@lat AS VARCHAR(20)) + ' ' +
CAST(@lon AS VARCHAR(20)) + ')', 4326)
其中@lat和@lon是所讨论城市的纬度和经度。
然后你可以查询表格......
SELECT [column1],[column2],[etc]
FROM [table]
WHERE @point.STBuffer(160934.4).STIntersects(geography::STPointFromText(
'POINT(' + CAST([lat] AS VARCHAR(20)) + ' ' +
CAST([lon] AS VARCHAR(20)) + ')', 4326) );
其中160934.4是100英里内的米数。
但这会很慢。如果你想做更多的空间工作,可以添加一个持久的计算列(因为lat和lon点实际上不会改变),然后使用空间索引。
ALTER TABLE [table]
ADD geo_point AS geography::STPointFromText('POINT(' + CAST([lat] AS VARCHAR(20))
+ ' ' + CAST([lon] AS VARCHAR(20)) + ')', 4326) PERSISTED;
CREATE SPATIAL INDEX spix_table_geopt
ON table(geo_point)
WITH ( BOUNDING_BOX = ( 0, 0, 500, 200 ) ); --you'd have to know your data
答案 1 :(得分:3)
ALTER PROCEDURE [dbo].[sp_StoresByZipArea] (@zip nvarchar(5), @Radius float) AS
DECLARE @LatRange float
DECLARE @LongRange float
DECLARE @LowLatitude float
DECLARE @HighLatitude float
DECLARE @LowLongitude float
DECLARE @HighLongitude float
DECLARE @istartlat float
DECLARE @istartlong float
SELECT @iStartlat=Latitude, @iStartLong=Longitude from zipcodes where zipcode=@ZIP
SELECT @LatRange = @Radius / ((6076 / 5280) * 60)
SELECT @LongRange = @Radius / (((cos((@iStartLat * 3.141592653589 / 180)) * 6076.) / 5280.) * 60)
SELECT @LowLatitude = @istartlat - @LatRange
SELECT @HighLatitude = @istartlat + @LatRange
SELECT @LowLongitude = @istartlong - @LongRange
SELECT @HighLongitude = @istartlong + @LongRange
/** Now you can create a SQL statement which limits the recordset of cities in this manner: **/
SELECT * FROM ZipCodes
WHERE (Latitude <= @HighLatitude) AND (Latitude >= @LowLatitude) AND (Longitude >= @LowLongitude) AND (Longitude <= @HighLongitude)