Skip to content

Instantly share code, notes, and snippets.

@elden1337
Last active January 18, 2018 13:19
Show Gist options
  • Save elden1337/ef4f2669b318ff23fac0d10983509454 to your computer and use it in GitHub Desktop.
Save elden1337/ef4f2669b318ff23fac0d10983509454 to your computer and use it in GitHub Desktop.
Quick calc to determine centerpoint and radius of circle enclosing a bounding box (helper to query Redis geospatial data)
using System;
using Microsoft.SqlServer.Types;
using System.Data.SqlTypes;
namespace circleradius
{
class Program
{
static void Main()
{
SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);
double lat1 = 15;
double lng1 = 11;
double lat2 = 35;
double lng2 = 32;
string lineString = string.Format("LINESTRING({0} {1}, {2} {3} )",lat1,lng1,lat2,lng2);
string rectangle = string.Format("POLYGON(({0} {1}, {0} {3}, {2} {3}, {2} {1}, {0} {1}))", lat1, lng1, lat2, lng2);
//make bounding box and hypothenuse
SqlGeometry bbox = SqlGeometry.STGeomFromText(new SqlChars(new SqlString(rectangle)), 4326);
SqlGeometry bboxDiagonal = SqlGeometry.STGeomFromText(new SqlChars(new SqlString(lineString)), 4326);
//get half length of diagonal (1/2 hypothenuse)
double circleRadius = double.Parse((bboxDiagonal.STLength() / 2).ToString());
//get centerpoint of bounding box
SqlGeometry circleCenter = bbox.STCentroid();
//not necessary for further spatial work, so just here to prove calc.
SqlDouble a = circleCenter.STX;
SqlDouble b = circleCenter.STY;
Console.WriteLine("r="+circleRadius);
Console.WriteLine("centerpoint: ("+a+" "+b+")");
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment