Distance between 2 geocodes

前端 未结 9 1457
一生所求
一生所求 2020-12-05 22:10

What is the formula for calculating the distance between 2 geocodes? I have seen some of the answers on this site but they basically say to rely on SQL Server 08 functions,

9条回答
  •  猫巷女王i
    2020-12-05 22:47

    This will do it for you in c#.

    Within the namespace put these:

     public enum DistanceType { Miles, Kilometers };
    
    public struct Position
    {
        public double Latitude;
        public double Longitude;
    }
    
    class Haversine
    {
    
        public double Distance(Position pos1, Position pos2, DistanceType type)
        {
            double preDlat = pos2.Latitude - pos1.Latitude;
            double preDlon = pos2.Longitude - pos1.Longitude;
            double R = (type == DistanceType.Miles) ? 3960 : 6371;
            double dLat = this.toRadian(preDlat);
            double dLon = this.toRadian(preDlon);
            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;
        }
    
        private double toRadian(double val)
        {
            return (Math.PI / 180) * val;
        }
    

    Then to utilise these in the main code:

    Position pos1 = new Position();
                        pos1.Latitude = Convert.ToDouble(hotelx.latitude);
                        pos1.Longitude = Convert.ToDouble(hotelx.longitude);
                        Position pos2 = new Position();
                        pos2.Latitude = Convert.ToDouble(lat);
                        pos2.Longitude = Convert.ToDouble(lng);
                        Haversine calc = new Haversine();
    
                        double result = calc.Distance(pos1, pos2, DistanceType.Miles);
    

提交回复
热议问题