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

87 lines
2.7 KiB
C#
Raw Normal View History

// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2024-02-03 21:01:53 +01:00
// Copyright © 2024 Clemens Fischer
// Licensed under the Microsoft Public License (Ms-PL)
using System;
using System.Globalization;
namespace MapControl
{
/// <summary>
/// A geographic bounding box with south and north latitude and west and east longitude values in degrees.
/// </summary>
2021-11-17 23:17:11 +01:00
#if !UWP
[System.ComponentModel.TypeConverter(typeof(BoundingBoxConverter))]
#endif
public class BoundingBox
{
2022-12-07 17:00:25 +01:00
private double south;
private double north;
public BoundingBox()
{
2022-12-07 17:00:25 +01:00
south = double.NaN;
north = double.NaN;
West = double.NaN;
East = double.NaN;
}
2022-12-07 17:00:25 +01:00
public BoundingBox(double latitude1, double longitude1, double latitude2, double longitude2)
{
2022-12-07 17:00:25 +01:00
South = Math.Min(latitude1, latitude2);
North = Math.Max(latitude1, latitude2);
West = Math.Min(longitude1, longitude2);
East = Math.Max(longitude1, longitude2);
}
2022-12-07 17:00:25 +01:00
public BoundingBox(Location location1, Location location2)
: this(location1.Latitude, location1.Longitude, location2.Latitude, location2.Longitude)
{
}
public double South
{
2022-08-06 10:40:59 +02:00
get => south;
set => south = Math.Min(Math.Max(value, -90d), 90d);
}
public double North
{
2022-08-06 10:40:59 +02:00
get => north;
set => north = Math.Min(Math.Max(value, -90d), 90d);
}
2022-12-07 23:34:42 +01:00
public double West { get; set; }
public double East { get; set; }
2022-12-07 23:34:42 +01:00
public virtual double Width => East - West;
public virtual double Height => North - South;
2022-12-07 23:34:42 +01:00
public virtual Location Center =>
2022-12-08 15:05:19 +01:00
HasValidBounds ? new Location((South + North) / 2d, (West + East) / 2d) : null;
public virtual bool HasValidBounds => South < North && West < East;
2022-12-01 22:48:08 +01:00
public static BoundingBox Parse(string boundingBox)
{
2022-12-01 22:48:08 +01:00
string[] values = null;
if (!string.IsNullOrEmpty(boundingBox))
{
values = boundingBox.Split(new char[] { ',' });
}
2022-12-01 22:48:08 +01:00
if (values?.Length != 4)
{
2021-12-05 17:16:14 +01:00
throw new FormatException("BoundingBox string must be a comma-separated list of four floating point numbers.");
}
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));
}
}
}