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

93 lines
2.9 KiB
C#
Raw Normal View History

// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2022-01-14 20:22:56 +01:00
// © 2022 Clemens Fischer
// Licensed under the Microsoft Public License (Ms-PL)
using System;
2021-11-17 23:17:11 +01:00
#if !WINUI && !UWP
using System.Windows;
#endif
namespace MapControl
{
/// <summary>
2022-02-23 23:19:32 +01:00
/// Elliptical Mercator Projection - EPSG:3395.
2018-12-20 21:55:12 +01:00
/// See "Map Projections - A Working Manual" (https://pubs.usgs.gov/pp/1395/report.pdf), p.44-45.
/// </summary>
public class WorldMercatorProjection : MapProjection
{
2022-01-19 16:43:00 +01:00
public const string DefaultCrsId = "EPSG:3395";
2020-04-17 14:40:14 +02:00
public static double ConvergenceTolerance { get; set; } = 1e-6;
public static int MaxIterations { get; set; } = 10;
public WorldMercatorProjection()
{
2022-03-05 18:40:57 +01:00
Type = MapProjectionType.NormalCylindrical;
2022-01-19 16:43:00 +01:00
CrsId = DefaultCrsId;
}
public override Vector GetRelativeScale(Location location)
{
var lat = location.Latitude * Math.PI / 180d;
var eSinLat = Wgs84Eccentricity * Math.Sin(lat);
2018-12-20 21:55:12 +01:00
var k = Math.Sqrt(1d - eSinLat * eSinLat) / Math.Cos(lat); // p.44 (7-8)
return new Vector(k, k);
}
public override Point LocationToMap(Location location)
{
return new Point(
2022-03-02 22:03:18 +01:00
Wgs84MeterPerDegree * location.Longitude,
Wgs84MeterPerDegree * LatitudeToY(location.Latitude));
}
public override Location MapToLocation(Point point)
{
return new Location(
2022-03-02 22:03:18 +01:00
YToLatitude(point.Y / Wgs84MeterPerDegree),
point.X / Wgs84MeterPerDegree);
}
public static double LatitudeToY(double latitude)
{
if (latitude <= -90d)
{
return double.NegativeInfinity;
}
if (latitude >= 90d)
{
return double.PositiveInfinity;
}
var lat = latitude * Math.PI / 180d;
2020-04-17 14:40:14 +02:00
return Math.Log(Math.Tan(lat / 2d + Math.PI / 4d) * ConformalFactor(lat)) * 180d / Math.PI; // p.44 (7-7)
}
public static double YToLatitude(double y)
{
2018-12-20 21:55:12 +01:00
var t = Math.Exp(-y * Math.PI / 180d); // p.44 (7-10)
var lat = Math.PI / 2d - 2d * Math.Atan(t); // p.44 (7-11)
var relChange = 1d;
2018-12-20 21:55:12 +01:00
for (var i = 0; i < MaxIterations && relChange > ConvergenceTolerance; i++)
{
2018-12-20 21:55:12 +01:00
var newLat = Math.PI / 2d - 2d * Math.Atan(t * ConformalFactor(lat)); // p.44 (7-9)
relChange = Math.Abs(1d - newLat / lat);
lat = newLat;
}
2018-12-20 21:55:12 +01:00
return lat * 180d / Math.PI;
}
private static double ConformalFactor(double lat)
{
var eSinLat = Wgs84Eccentricity * Math.Sin(lat);
return Math.Pow((1d - eSinLat) / (1d + eSinLat), Wgs84Eccentricity / 2d);
}
}
}