【问题标题】:How to get distance between two locations in Windows Phone 8.1如何在 Windows Phone 8.1 中获取两个位置之间的距离
【发布时间】:2015-02-17 19:10:51
【问题描述】:
【问题讨论】:
标签:
c#
windows-phone-8
windows-phone-8.1
.net-4.5
【解决方案1】:
GeoCoordinate.GetDistanceTo() 位于 System.Device.Location 命名空间中。但是 Windows 8.1(运行时应用程序)应用程序使用 Windows.Devices.Geolocation 命名空间,而 GetDistanceTo() 方法不存在。
因此您可以使用 Haversine 公式自行计算距离。这里是wikipedia Haversine page,你可以从那里了解公式。
您可以使用以下 C# 代码,该代码使用 Haversine 公式计算两个坐标之间的距离。
using System;
namespace HaversineFormula
{
/// <summary>
/// The distance type to return the results in.
/// </summary>
public enum DistanceType { Miles, Kilometers };
/// <summary>
/// Specifies a Latitude / Longitude point.
/// </summary>
public struct Position
{
public double Latitude;
public double Longitude;
}
class Haversine
{
/// <summary>
/// Returns the distance in miles or kilometers of any two
/// latitude / longitude points.
/// </summary>
public double Distance(Position pos1, Position pos2, DistanceType type)
{
double R = (type == DistanceType.Miles) ? 3960 : 6371;
double dLat = this.toRadian(pos2.Latitude - pos1.Latitude);
double dLon = this.toRadian(pos2.Longitude - pos1.Longitude);
double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Cos(this.toRadian(pos1.Latitude)) * Math.Cos(this.toRadian(pos2.Latitude)) *
Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
double d = R * c;
return d;
}
/// <summary>
/// Convert to Radians.
/// </summary>
private double toRadian(double val)
{
return (Math.PI / 180) * val;
}
}