0

This is my code for the Haversine formula based off of this and the answer of this question:

$scope.getCoordDistance = function (myLat, myLon, locLat, locLon) {
        var lat2 = 41.894993;
        var lon2 = -88.459239;
        var lat1 = $scope.locLat;
        var lon1 = $scope.locLon;

        var R = 3959;
        var x1 = lat1 - lat2;
        var dLat = x1 * Math.PI / 180;
        var x2 = lon1 - lon2;
        var dLon = x2 * Math.PI / 180;
        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
          Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
          Math.sin(dLon / 2) * Math.sin(dLon / 2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        d = R * c;
        return d;
    }

I tested this with 3 different locations an they are all way off, the first location says its 14790.7 miles away when it is actually 44.1 miles away, every location is off by a different amount. Some are off by a small amount, others a very large amount. Is something wrong with my math here? If not, why wont this code work correctly? Here is a link to a plunk with my full project: http://plnkr.co/edit/nRQc7Ym0lsaK6jQwd626?p=preview
Thanks in advanced for any help!!!

Community
  • 1
  • 1
Ian Pennebaker
  • 233
  • 4
  • 15

1 Answers1

-1

The actual calculation works out the distance. The problem is how you use it in your function.

You pass 4 parameters in function myLat, myLon, locLat, locLon and then don't use them. I assume that you are still calling function in a forEach loop. Try this

Outside forEach

var myLat = 41.894993;
var myLon = -88.459239;

Inside forEach

var locLat = $scope.locLat;
var locLon = $scope.locLon;
getCoordDistance(myLat, myLon, locLat, locLon)
etc.

Function

$scope.getCoordDistance = function (myLat, myLon, locLat, locLon) {
       var R = 3959;
        var x1 = lat1 - lat2;
        var dLat = x1 * Math.PI / 180;
        var x2 = lon1 - lon2;
        var dLon = x2 * Math.PI / 180;
        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
          Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
          Math.sin(dLon / 2) * Math.sin(dLon / 2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        d = R * c;
        return d;
    }   
david strachan
  • 7,174
  • 2
  • 23
  • 33