[Solved] Issue returning function in AngularJS Service [closed]


The error here is that lat is not identified as a function on ‘origin’.

Now your factory should return an object that contains a function and not a function.

You will perform your call to that function after injecting the function to whereever you want.

web.factory('distance', function() {

    // Should this be here???
    Number.prototype.toRad = function() {
        return this * Math.PI / 180;
    };

    return
        {
          calculate:function(origin, destination) {
                 var R = 6371; // Radius of the earth in km
                 var dLat = (origin.lat()-destination.lat()).toRad();  // Javascript functions in radians
                 var dLon = (origin.lng()-destination.lng()).toRad();
                 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                 Math.cos(origin.lat().toRad()) * Math.cos(destination.lat().toRad()) *
                 Math.sin(dLon/2) * Math.sin(dLon/2);
                 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                 return R * c; // Distance in km
        }
    };
});

You should use: distance.calculate(a,b) where you need.

7

solved Issue returning function in AngularJS Service [closed]