Joyce de Lanna
Joyce de Lanna

Reputation: 1543

Trying to get the distance with C#

I need to discover which is the closer item in main list which its items have latitude and longitude. I came across this script, and I am using to return the distance in kilometers...but the item returned isn't is the closer item...does someone know why it didn't work? thank u very much! I am using xamarin forms c# my English is not that good, sorry.

public static Loja EncontraLojaPerto(List<Loja> lojaList, double lat1, 
double lon1, char unit)
    {
        Loja lojaProxima = new Loja();
        double distAuxiliar = -1;

        foreach (var item in lojaList)
        {
            double lat2 = Convert.ToDouble(item.latitude.Replace('.',','));
            double lon2 = Convert.ToDouble(item.longitude.Replace('.',','));

            Func<double, double> deg2Rad = (x) => (x * (Math.PI / 180));
            Func<double, double> rad2Deg = (x) => (x / Math.PI * 180.0);

            var theta = lon1 - lon2;
            var dist = Math.Sin(deg2Rad(lat1)) * Math.Sin(deg2Rad(lat2)) + Math.Cos(deg2Rad(lat1)) * Math.Cos(deg2Rad(lat2)) * Math.Cos(deg2Rad(theta));

            dist = Math.Acos(dist);
            dist = rad2Deg(dist);
            dist = dist * 60 * 1.1515;

            switch (unit)
            {
                case 'K':
                    dist = dist * 1.609344;
                    break;
                case 'N':
                    dist = dist * 0.8684;
                    break;
            }

            //verificando se essa pode ser a distância menor
            int retval = distAuxiliar.CompareTo(dist);

            if (retval > 0 || distAuxiliar.Equals(-1))
            {
                distAuxiliar = dist;
                lojaProxima = item;
            }
        }

        return lojaProxima;
    }

I was searching for a answer and I found it: here, in Brazil we use ',' instead '.' and '.' instead ','...then, My webservice give me a numver with '.' when I need a ',', then I used .Replace to replace the '.', but, when I use it, the number change its quantity of character (if it was 123.4300 now it is 123,43)...when I used the Replace, the numbers worked but the foreach never finish and I never arrive in the 'return' line...

Upvotes: 0

Views: 72

Answers (1)

InBetween
InBetween

Reputation: 32780

Your implementation of the haversine formula seems to be wrong. It should be:

a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
c = 2 ⋅ atan2( √a, √(1−a) )
d = R ⋅ c

where φ is latitude, λ is longitude and R is earth’s radius (mean radius = 6,371km);

Source

Upvotes: 1

Related Questions