80 lines
2.9 KiB
C#
80 lines
2.9 KiB
C#
using Manager.DTOs;
|
|
using NetTopologySuite;
|
|
using NetTopologySuite.Geometries;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text.Json;
|
|
using System;
|
|
|
|
namespace ManagerService.Helpers
|
|
{
|
|
public static class GeometryMapper
|
|
{
|
|
public static GeometryDTO ToDto(this Geometry geometry)
|
|
{
|
|
return geometry switch
|
|
{
|
|
Point point => new GeometryDTO
|
|
{
|
|
type = "Point",
|
|
coordinates = new List<double> { point.X, point.Y }
|
|
},
|
|
LineString line => new GeometryDTO
|
|
{
|
|
type = "LineString",
|
|
coordinates = line.Coordinates
|
|
.Select(coord => new List<double> { coord.X, coord.Y })
|
|
.ToList()
|
|
},
|
|
Polygon polygon => new GeometryDTO
|
|
{
|
|
type = "Polygon",
|
|
coordinates = new List<List<List<double>>>
|
|
{
|
|
polygon.ExteriorRing.Coordinates
|
|
.Select(coord => new List<double> { coord.X, coord.Y })
|
|
.ToList()
|
|
}
|
|
},
|
|
_ => throw new NotSupportedException($"Geometry type {geometry.GeometryType} not supported.")
|
|
};
|
|
}
|
|
|
|
public static Geometry FromDto(this GeometryDTO dto, GeometryFactory factory = null!)
|
|
{
|
|
factory ??= NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
|
|
|
|
|
|
return dto.type switch
|
|
{
|
|
"Point" => CreatePoint(dto, factory),
|
|
"LineString" => CreateLineString(dto, factory),
|
|
"Polygon" => CreatePolygon(dto, factory),
|
|
_ => throw new NotSupportedException($"DTO type {dto.type} not supported.")
|
|
};
|
|
}
|
|
|
|
private static Point CreatePoint(GeometryDTO dto, GeometryFactory factory)
|
|
{
|
|
var coords = ((JsonElement)dto.coordinates).Deserialize<List<double>>();
|
|
var point = factory.CreatePoint(new Coordinate(coords[0], coords[1]));
|
|
return point;
|
|
}
|
|
|
|
private static LineString CreateLineString(GeometryDTO dto, GeometryFactory factory)
|
|
{
|
|
var coords = ((JsonElement)dto.coordinates).Deserialize<List<List<double>>>();
|
|
var coordinates = coords.Select(c => new Coordinate(c[0], c[1])).ToArray();
|
|
return factory.CreateLineString(coordinates);
|
|
}
|
|
|
|
private static Polygon CreatePolygon(GeometryDTO dto, GeometryFactory factory)
|
|
{
|
|
var rings = ((JsonElement)dto.coordinates).Deserialize<List<List<List<double>>>>();
|
|
var exterior = rings.First().Select(c => new Coordinate(c[0], c[1])).ToArray();
|
|
return factory.CreatePolygon(exterior);
|
|
}
|
|
}
|
|
|
|
}
|