Search code examples
javascriptfunctionreturn-valuenested-loops

Unable to return value from nested function in Javascript


Hey guys i prepare a project with html5 geolocation that will calculate the distance. I've got a problem with returning value from nested function in Javascript, can anyone help me ?

Here is my code:

/* DISTANCE CALCULATOR FUNCTION */

function distanceCalc(latitudeB,longitudeB) {
  var result;

  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(showPosition);
  }

  function showPosition(position) {
    calc(position.coords.latitude,position.coords.longitude);
  } 

  function calc(latitudeA,longitudeA) {
    var lat1 = latitudeA;
    var lon1 = longitude;
    var lat2 = latitudeB;
    var lon2 = longitudeB;
    var R = 6371; // km  
    var dLat = (lat2-lat1)*Math.PI/180;  
    var dLon = (lon2-lon1)*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.asin(Math.sqrt(a));   
    var d = R * c;
    result = d.toFixed(1);
    return result;
  }

  return result;

}

I would like to do something like

var test = distanceCalc(44.35678,33.78546);

This code doesnt work, returns NAN value


Solution

  • There's so many errors on your script and logic. Also, when getting geolocation coords a assync call is made. Try it out:

    var DistanceCalc = function(latitudeB, longitudeB, onReadyCallback) {   
        this.latitudeB  = latitudeB;
        this.longitudeB = longitudeB;
        this.callback  = onReadyCallback;
    
        //calling this.calc() here is ok...
    };
    
    DistanceCalc.prototype.calc = function()
    {
        var __calc = function(position) {       
            var lat1 = position.coords.latitude;
            var lon1 =  position.coords.longitude;
            var lat2 = this.latitudeB;
            var lon2 = this.longitudeB;
    
            var R = 6371; // km  
            var dLat = (lat2-lat1)*Math.PI/180;  
            var dLon = (lon2-lon1)*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.asin(Math.sqrt(a));   
            var d = R * c;  
            var result = d.toFixed(1);
    
            this.callback(result);
        }.bind(this); //bind to DistanceCalc object context
    
        if (navigator.geolocation) {
            navigator.geolocation.watchPosition(__calc);
        } else {
            console.log("geolocation is not available");
            this.callback(null);
        }       
    };  
    
    function doSomething(result) {
        console.log(">>> ", result);
    }
    
    var calculator = new DistanceCalc(44.35678, 33.78546, doSomething);
    calculator.calc();