无法从Javascript中的嵌套函数返回值

时间:2015-02-09 16:14:46

标签: javascript function return-value nested-loops

嘿伙计们,我准备了一个用html5地理位置来计算距离的项目。我在Javascript中从嵌套函数返回值时遇到问题,有人可以帮助我吗?

这是我的代码:

/* 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;

}

我想做点什么

var test = distanceCalc(44.35678,33.78546);

此代码不起作用,返回NAN值

1 个答案:

答案 0 :(得分:0)

你的脚本和逻辑上有很多错误。此外,当获得地理定位坐标时,会进行同步调用。 试试吧:

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();