2012-11-26 28 views
-1

可能重複:
toRad() javascript function throwing error地理定位功能不起作用! JavaScript的

所以首先我有這兩個p標籤

<p id="pos"></p> 
<p id="dist"></p> 

如果我把 「POS」 我的位置和距離我之間和「dist」中的紐約。 我得到了這兩個按鈕來觸發JS功能:

<button onclick="getLocation()">Get position</button> 
<button onclick="calcDistance()">Calculate distance to NY</button> 

這裏是所有的腳本:

var x=document.getElementById("pos"); 
var d=document.getElementById("dist"); 
var startPos; 
function getLocation(){ 
     navigator.geolocation.getCurrentPosition(function(position) { 
     startPos = position; 
     x.innerHTML= "<h3>Your position</h3>" + 
     "Latitude: " + startPos.coords.latitude + 
     "<br>Longitude: " + startPos.coords.longitude; 
     }); 
}; 
function calcDistance(){ 
    var distt = calculateDistance(startPos.coords.latitude, startPos.coords.longitude, 40.28371627, -73.994901); 
    d.innerHTML = distt.toFixed(1); 
}; 

function calculateDistance(lat1,lon1,lat2,lon2) { 
    var R = 6371; 
    var dLat = (lat2-lat1).toRad(); 
    var dLon = (lon2-lon1).toRad(); 
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
      Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
      Math.sin(dLon/2) * Math.sin(dLon/2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    return R * c; 
} 

我calcDistance按鈕沒有工作,我沒有一個線索是什麼問題是。 我試着只把數字放在calculateDistance()中,但它仍然不起作用。怎麼來的?

+3

因爲'.toRad()'不是數字的號碼功能? – apsillers

+0

我們的老師要求我們使用這個函數,所以我認爲我們不會在意它。那麼爲什麼toRad使它無法工作? –

+1

你在調用一個不存在的函數。也許你的老師要求你使用定義'toRad'的庫?或者,也許你的老師希望你使用具有'toRad'功能的語言?或者你的老師只是希望你自己定義它。 – apsillers

回答

2

將這個上面你的JS:

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

正如@apsillers說,.toRad()是不是原生功能。爲了將來的參考,你應該使用一個Web控制檯,它會讓你知道錯誤是什麼。在這種情況下,您可以:

Uncaught TypeError: Object -0.123871823 has no method 'toRad'

+2

注意到這個問題本質上是一樣的:http://stackoverflow.com/questions/5260423/torad-javascript-function-throwing-error –

+0

是的,也許可以作爲一個愚蠢的關閉。編輯:投票。 – Prisoner

+0

謝謝!顯然,我忘記了包括這個if(typeof(Number.prototype.toRad)===「undefined」)Number.prototype.toRad = function(){this.Math.PI/180;}返回這個數組。 }; (number.prototype.toDeg)===「undefined」){ } if(typeof(Number.prototype.toDeg)===「undefined」){Number.prototype.toDeg = function(){ return this * 180/Math.PI; }; }' –