XAML-Map-Control/MapControl/Shared/BoundingBox.cs

50 lines
1.9 KiB
C#
Raw Normal View History

2025-02-27 18:46:32 +01:00
using System;
using System.Globalization;
2026-04-13 17:14:49 +02:00
namespace MapControl;
/// <summary>
/// A geographic bounding box with south and north latitude and west and east longitude values in degrees.
/// </summary>
2024-05-22 11:25:32 +02:00
#if UWP || WINUI
2026-04-13 17:14:49 +02:00
[Windows.Foundation.Metadata.CreateFromString(MethodName = "Parse")]
2024-04-11 14:57:54 +02:00
#else
2026-04-13 17:14:49 +02:00
[System.ComponentModel.TypeConverter(typeof(BoundingBoxConverter))]
#endif
2026-04-13 17:14:49 +02:00
public class BoundingBox(double latitude1, double longitude1, double latitude2, double longitude2)
{
public double South { get; } = Math.Min(Math.Max(Math.Min(latitude1, latitude2), -90d), 90d);
public double North { get; } = Math.Min(Math.Max(Math.Max(latitude1, latitude2), -90d), 90d);
public double West { get; } = Math.Min(longitude1, longitude2);
public double East { get; } = Math.Max(longitude1, longitude2);
public override string ToString()
{
2026-04-13 17:14:49 +02:00
return string.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", South, West, North, East);
}
2026-04-13 17:14:49 +02:00
/// <summary>
/// Creates a BoundingBox instance from a string containing a comma-separated sequence of four floating point numbers.
/// </summary>
public static BoundingBox Parse(string boundingBox)
{
string[] values = null;
if (!string.IsNullOrEmpty(boundingBox))
2025-08-14 13:11:25 +02:00
{
2026-04-13 17:14:49 +02:00
values = boundingBox.Split(',');
2025-08-14 13:11:25 +02:00
}
2026-04-13 17:14:49 +02:00
if (values == null || values.Length != 4 && values.Length != 5)
{
2026-04-13 17:14:49 +02:00
throw new FormatException($"{nameof(BoundingBox)} string must contain a comma-separated sequence of four floating point numbers.");
}
2026-04-13 17:14:49 +02:00
return new BoundingBox(
double.Parse(values[0], NumberStyles.Float, CultureInfo.InvariantCulture),
double.Parse(values[1], NumberStyles.Float, CultureInfo.InvariantCulture),
double.Parse(values[2], NumberStyles.Float, CultureInfo.InvariantCulture),
double.Parse(values[3], NumberStyles.Float, CultureInfo.InvariantCulture));
}
}