using System.Collections.Generic;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
private static readonly PrecisionModel DefaultPrecisionModel = new(1000000.0);
private static readonly GeometryFactory DefaultGeometryFactory = new GeometryFactoryEx(DefaultPrecisionModel, 4326)
{OrientationOfExteriorRing = LinearRingOrientation.CounterClockwise};
private static readonly JsonSerializer Serializer = GeoJsonSerializer.Create(new JsonSerializerSettings{Formatting = Formatting.Indented}, DefaultGeometryFactory);
public static void Main()
var coordinates = new List<Coordinate>();
Console.WriteLine("Build a Polygon: Enter at least four non-intersecting points to create a GeoJSON polygon.");
Console.WriteLine("Enter a latitude and longitude pair separated by a comma and a space " + "(example: -90, 180; enter nothing to build the polygon or q to quit without building the polygon): ");
input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
if ("q".Equals(input, StringComparison.InvariantCultureIgnoreCase))
Console.WriteLine("Exiting.");
var rawCoordinates = input.Trim().Split(", ");
if (rawCoordinates.Length != 2)
Console.WriteLine("Both a latitude and a longitude must be supplied. Try again.");
var latitudeResult = double.TryParse(rawCoordinates[0], out var latitude);
Console.WriteLine("Latitude was not a number. Try again.");
var longitudeResult = double.TryParse(rawCoordinates[1], out var longitude);
Console.WriteLine("Longitude was not a number. Try again.");
if (!TryAddCoordinate(longitude, latitude, out var result))
while (!string.IsNullOrWhiteSpace(input));
if (coordinates.Count < 4)
Console.WriteLine("Not enough points to create a polygon, exiting.");
if (!coordinates.First().Equals(coordinates.Last()))
Console.WriteLine("Coordinates do not form a closed ring. Will attempt to close them automagically.");
coordinates.Add(coordinates.First());
var geom = DefaultGeometryFactory.CreatePolygon(coordinates.ToArray());
Console.WriteLine("Resulting polygon was not valid. The points may be intersecting.");
Console.WriteLine("Polygon is correct (probably); writing it out to the console.");
using (var stringWriter = new StringWriter())
using (var jsonWriter = new JsonTextWriter(stringWriter))
Serializer.Serialize(jsonWriter, geom);
Console.WriteLine(stringWriter.ToString());
static bool TryAddCoordinate(double longitude, double latitude, out Coordinate coordinate)
if (longitude is> 180.0 or < -180.0)
Console.WriteLine($"Longitude is outside of the [-180, 180] range (value: {longitude}).");
if (latitude is> 90.0 or < -90.0)
Console.WriteLine($"Latitude is outside of the [-90, 90] range (value: {longitude}).");
coordinate = new Coordinate(longitude, latitude);