2015-02-09 90 views
0

嘿,我準備了一個項目,其中會計算距離的html5地理位置。我有一個從Javascript中嵌套函數返回值的問題,任何人都可以幫助我嗎?無法從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

問題與返回值無關。 – Oriol 2015-02-09 16:16:19

+1

您是否試過通過調試器運行它並查看會發生什麼? – 2015-02-09 16:16:29

+3

注意事項:應用正確的縮進可以讓你的生活更輕鬆。 – melancia 2015-02-09 16:17:13

回答

0

有你的腳本這麼多的錯誤,邏輯。另外,在獲取地理位置座標時,會進行assync調用。 試一試:

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

謝謝你哥們 – billo 2015-02-11 00:01:36