Skip to content

Instantly share code, notes, and snippets.

@dvhthomas
Created October 5, 2009 15:43
Show Gist options
  • Select an option

  • Save dvhthomas/202198 to your computer and use it in GitHub Desktop.

Select an option

Save dvhthomas/202198 to your computer and use it in GitHub Desktop.
Get center of NTS feature
/// <summary>
/// Finds the center of points and polygons, or the mid point
/// of a line.
/// </summary>
/// <param name="feature">ESRI feature</param>
/// <returns>x,y coordinates of centroid/mid point</returns>
private double[] DetermineCenter(IFeature feature)
{
double x = 0;
double y = 0;
if (feature == null) return new[] {x, y};
try
{
var environment = _context.CreateObject("esriGeometry.GeometryEnvironment") as GeometryEnvironment;
_context.SetObject("geometryFactory", environment);
var factory = (IGeometryFactory3) environment;
var converter = new Converters(factory);
IGeometry geometry = converter.ConvertESRIToGeoAPI(feature.Shape);
if (geometry is IPoint || geometry is IPolygon)
{
x = geometry.Centroid.X;
y = geometry.Centroid.Y;
}
else if (geometry is ILineString)
{
// Use linear referencing to the get point half
// way along the line.
double midlength = geometry.Length/2;
var lengthIndexedLine = new LengthIndexedLine(geometry);
ICoordinate midpoint = lengthIndexedLine.ExtractPoint(midlength);
x = midpoint.X;
y = midpoint.Y;
}
}
finally
{
_context.Remove("geometryFactory");
}
return new[] {x, y};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment