问题
I have several thousand records in a development environment, each associated with a centroid of a particular zip code. For testing purposes, I need to randomly scatter each SQL Server geography point 0-5 miles around that centroid.
So in the example below I want to update LocationGeo so it is 0-5 miles away from its respective ZipGeo. Do I have to use a random % applied to each Lon/Lat or is there a better option?
LocationID int
LocationGeo geography
ZipCode char(5)
ZipCode char(5)
ZipGeo geography
回答1:
I found an answer from this post https://gis.stackexchange.com/a/25883/37373
I adapted the response into SQL Server code.
DECLARE @geo as GEOGRAPHY,@newgeo as GEOGRAPHY
SET @geo = (SELECT ZipGeo FROM Location.ZipCodes WHERE ZipCode='90210')
DECLARE @r float,@t float, @w float, @x float, @y float, @u float, @v float;
SET @u=RAND();
SET @v=RAND();
--8046m = ~ 5 miles
SET @r= 8046/(111300*1.0);
SET @w = @r * sqrt(@u);
SET @t = 2 * PI() * @v;
SET @x = @w * cos(@t);
SET @y = @w * sin(@t);
SET @x = @x / cos(@geo.Lat);
SET @newgeo = geography::STPointFromText('POINT('+CAST(@geo.Long+@x AS VARCHAR(MAX))+' '+CAST(@geo.Lat+@y AS VARCHAR(MAX))+')',4326)
--Convert the distance back to miles to validate
SELECT @geo.STDistance(@newgeo)/1609.34
来源:https://stackoverflow.com/questions/26953152/sql-server-generating-random-spatial-geography-around-point