Calculate distance between two points in google maps V3

后端 未结 15 1699
醉梦人生
醉梦人生 2020-11-22 02:27

How do you calculate the distance between two markers in Google maps V3? (Similar to the distanceFrom function inV2.)

Thanks..

15条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 02:45

    OFFLINE SOLUTION - Haversine Algorithm

    In Javascript

    var _eQuatorialEarthRadius = 6378.1370;
    var _d2r = (Math.PI / 180.0);
    
    function HaversineInM(lat1, long1, lat2, long2)
    {
        return (1000.0 * HaversineInKM(lat1, long1, lat2, long2));
    }
    
    function HaversineInKM(lat1, long1, lat2, long2)
    {
        var dlong = (long2 - long1) * _d2r;
        var dlat = (lat2 - lat1) * _d2r;
        var a = Math.pow(Math.sin(dlat / 2.0), 2.0) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r) * Math.pow(Math.sin(dlong / 2.0), 2.0);
        var c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
        var d = _eQuatorialEarthRadius * c;
    
        return d;
    }
    
    var meLat = -33.922982;
    var meLong = 151.083853;
    
    
    var result1 = HaversineInKM(meLat, meLong, -32.236457779983745, 148.69094705162837);
    var result2 = HaversineInKM(meLat, meLong, -33.609020205923713, 150.77061469270831);
    

    C#

    using System;
    
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("Hello World");
    
            var meLat = -33.922982;
            double meLong = 151.083853;
    
    
            var result1 = HaversineInM(meLat, meLong, -32.236457779983745, 148.69094705162837);
            var result2 = HaversineInM(meLat, meLong, -33.609020205923713, 150.77061469270831);
    
            Console.WriteLine(result1);
            Console.WriteLine(result2);
        }
    
        static double _eQuatorialEarthRadius = 6378.1370D;
        static double _d2r = (Math.PI / 180D);
    
        private static int HaversineInM(double lat1, double long1, double lat2, double long2)
        {
            return (int)(1000D * HaversineInKM(lat1, long1, lat2, long2));
        }
    
        private static  double HaversineInKM(double lat1, double long1, double lat2, double long2)
        {
            double dlong = (long2 - long1) * _d2r;
            double dlat = (lat2 - lat1) * _d2r;
            double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
            double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
            double d = _eQuatorialEarthRadius * c;
    
            return d;
        }
    }
    

    Reference: https://en.wikipedia.org/wiki/Great-circle_distance

提交回复
热议问题