Create a SqlGeography Polygon Circle from the Center and Radius

I would like to save a circle in the geography field of sql-server 2008 using C #.

In C #, I have latitude, longitude, and radius, but I just can't find a way to calculate the polygon that will represent the circle and create SqlGeography from it.

I tried to execute the following function to create a polygon:

  private List<Coordinate> getCirclePoints(Coordinate center, int radius, int speed) //speed 1: draws 360 sides, 2 draws 180 etc... { var centerLat = (center.Latitude * Math.PI) / 180.0; //rad var centerLng = (center.Longitude * Math.PI) / 180.0; //rad var dist = (float)radius / 6371.0; //d = angular distance covered on earth surface var circlePoints = new List<Coordinate>(); for (int x = 0; x <= 360; x += speed) { var brng = x * Math.PI / 180.0; //rad var latitude = Math.Asin(Math.Sin(centerLat) * Math.Cos(dist) + Math.Cos(centerLat) * Math.Sin(dist) * Math.Cos(brng)); var longitude = ((centerLng + Math.Atan2(Math.Sin(brng) * Math.Sin(dist) * Math.Cos(centerLat), Math.Cos(dist) - Math.Sin(centerLat) * Math.Sin(latitude))) * 180.0) / Math.PI; circlePoints.Add(new Coordinate((latitude * 180.0) / Math.PI, longitude)); } return circlePoints; } 

And then try converting this List<Coordinate> to a parsed string:

  var s = "POLYGON((" + string.Join(",", points.ConvertAll(p => p.Longitude + " " + p.Latitude).ToArray()) + "))"; var poly = SqlGeography.STPolyFromText(new System.Data.SqlTypes.SqlChars((SqlString)s), 4326); 

But he always complains that the polygon should be in the same hemisphere, where I am sure that it is.

Am I on the right track? Is there any other (simpler) way to do this?

+8
c # sql-server geospatial sqlgeography
source share
1 answer

OK, I found the answer myself. The trick is to create a point

 var point = SqlGeography.Point(latitude, longitude, 4326); 

Then create a buffer around the point

 var poly = point.BufferWithTolerance(radiusInMeter, 0.01, true); //0.01 is to simplify the polygon to keep only a few sides 

Then you could just create an SqlCommand and add a polygon as a parameter:

 var param = new SqlParameter(@"Polygon", poly); param.UdtTypeName = "Geography"; command.Parameters.Add(param); 

Hope this helps someone else in the future!

+19
source share

All Articles