Search code examples
javascriptangularjsangularjs-service

Issue returning function in AngularJS Service


Here is my service:

web.factory('distance', function() {
    Number.prototype.toRad = function() {
        return this * Math.PI / 180;
    };

    return 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
    };
});

Returning the function in my distance service is bombing out. Apparently it cannot see the method called origin.lat(). I thought in javascript you didn't have to initialize anything as a type prior?

Here is the error i am getting in chrome at the first occurence of "origin.lat()":

Uncaught TypeError: undefined is not a function

Any help appreciated. Thanks


Solution

  • 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.