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

120 lines
3.3 KiB
C#
Raw Normal View History

// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
// © 2020 Clemens Fischer
2012-07-07 17:19:10 +02:00
// Licensed under the Microsoft Public License (Ms-PL)
using System;
2012-05-04 12:52:20 +02:00
using System.Globalization;
namespace MapControl
{
/// <summary>
/// A geographic location with latitude and longitude values in degrees.
2012-05-04 12:52:20 +02:00
/// </summary>
#if !WINDOWS_UWP
[System.ComponentModel.TypeConverter(typeof(LocationConverter))]
#endif
public class Location : IEquatable<Location>
2012-05-04 12:52:20 +02:00
{
private double latitude;
private double longitude;
2012-05-04 12:52:20 +02:00
public Location()
{
}
public Location(double latitude, double longitude)
2012-05-04 12:52:20 +02:00
{
Latitude = latitude;
Longitude = longitude;
2012-05-04 12:52:20 +02:00
}
public double Latitude
{
get { return latitude; }
set { latitude = Math.Min(Math.Max(value, -90d), 90d); }
}
public double Longitude
{
get { return longitude; }
set { longitude = value; }
}
public bool Equals(Location location)
{
2017-08-04 21:38:58 +02:00
return location != null
&& Math.Abs(location.latitude - latitude) < 1e-9
&& Math.Abs(location.longitude - longitude) < 1e-9;
}
public override bool Equals(object obj)
{
return Equals(obj as Location);
}
public override int GetHashCode()
{
return latitude.GetHashCode() ^ longitude.GetHashCode();
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0:F5},{1:F5}", latitude, longitude);
}
public static Location Parse(string locationString)
2012-05-04 12:52:20 +02:00
{
Location location = null;
if (!string.IsNullOrEmpty(locationString))
{
var values = locationString.Split(new char[] { ',' });
if (values.Length != 2)
{
throw new FormatException("Location string must be a comma-separated pair of double values.");
}
location = new Location(
double.Parse(values[0], NumberStyles.Float, CultureInfo.InvariantCulture),
double.Parse(values[1], NumberStyles.Float, CultureInfo.InvariantCulture));
}
return location;
2012-05-04 12:52:20 +02:00
}
/// <summary>
/// Normalizes a longitude to a value in the interval [-180..180].
/// </summary>
public static double NormalizeLongitude(double longitude)
2012-05-04 12:52:20 +02:00
{
2013-12-20 17:05:10 +01:00
if (longitude < -180d)
{
2013-12-20 17:05:10 +01:00
longitude = ((longitude + 180d) % 360d) + 180d;
}
2013-12-20 17:05:10 +01:00
else if (longitude > 180d)
{
2013-12-20 17:05:10 +01:00
longitude = ((longitude - 180d) % 360d) - 180d;
}
return longitude;
2012-05-04 12:52:20 +02:00
}
internal static double NearestLongitude(double longitude, double referenceLongitude)
{
longitude = NormalizeLongitude(longitude);
if (longitude > referenceLongitude + 180d)
{
longitude -= 360d;
}
else if (longitude < referenceLongitude - 180d)
{
longitude += 360d;
}
return longitude;
}
2012-05-04 12:52:20 +02:00
}
}