0
distance(lon1, lat1, lon2, lat2) {

       var R = 6371; // Radius of the earth in km

        var dLat = (lat2-lat1).toRad();  // Javascript functions in radians

         var dLon = (lon2-lon1).toRad(); 

        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +

           Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 

            Math.sin(dLon/2) * Math.sin(dLon/2); 

          var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 

            var d = R * c; // Distance in km

                 return d;

          }

If I use this function in which I use a toRad() function. whenever I use it it will give an error:

Property toRad() does not exist type number.

Please help me what's the reason is that I have to import something?

1 Answers1

0

You should write your own toRad function like this:

function toRad(Value) {
        return Value * Math.PI / 180;
    }

An then use it in a functional way:

function distance(lon1, lat1, lon2, lat2) {
        var R = 6371;
        var dLat = toRad(lat2 - lat1);
        var dLon = toRad(lon2 - lon1);

        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);

        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        var d = R * c; 

        return d;
    }

Btw, are you writing your app in Ionic Angular? Shouldn't you be using Typescript rather than JavaScript?

elnezah
  • 425
  • 5
  • 17
  • Yes I am using Typescript but I didn't get any other solution so I used this one. If I pass lat , long value through geocoder it doesn't give me answer – Mahak Garg May 26 '20 at 10:15
  • You can write Javascript in Typescript, this will work, i.e., my solution should work in your code. I prefer TS because tries to be fix typed, you could make the arguments of the function fix to `number`. Also lint will refer `let` rather than `var` (will only affect the scope, so no effect in your snippet). – elnezah May 26 '20 at 14:26