如何在Windows Phone 8.1中获得两个位置之间的距离

问题描述:

在Windows Phone 8中似乎有方法

In Windows Phone 8 there seems to be method

   GeoCoordinate.GetDistanceTo()

用于计算两个位置之间的距离。 (即使找不到该方法的参考页。)

for calculating distances between two locations. (Even if the reference page for the method is not found.)

但是整个 Windows Phone 8.1地理位置命名空间

我根本找不到计算两个位置之间距离的方法。

I can't find a method to calculate distance between two locations at all.

如何在WP8.1中计算两个位置之间的距离?

How to calculate distance between two locations in WP8.1?

GeoCoordinate.GetDistanceTo() System.Device中找到。位置命名空间。但是Windows 8.1(运行时应用程序)应用程序使用 Windows.Devices.Geolocation 命名空间,其中不存在 GetDistanceTo()方法。

GeoCoordinate.GetDistanceTo() is found in System.Device.Location namespace. But windows 8.1 (Runtime apps) apps use Windows.Devices.Geolocation namespace where GetDistanceTo() method is not present.

因此,您可以使用 Haversine公式自己计算距离。这是维基百科Haversine页面,您可以从那里了解该公式。

So you can calculate the distance yourself by using the Haversine formula. Here is the wikipedia Haversine page, you can know about the formula from there.

您可以使用下面的C#代码,该代码使用Haversine公式计算两个坐标之间的距离。

You can use the below C# code which uses Haversine formula to calculate the distance between two coordinates.

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;  
    }  
}