地理位置功能不起作用!使用Javascript

时间:2012-11-26 17:09:00

标签: javascript html5 geolocation

  

可能重复:
  toRad() javascript function throwing error

首先我得到了这两个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()中,但它仍然不起作用。怎么样?

1 个答案:

答案 0 :(得分:2)

把它放在你的JS上面:

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

正如@apsillers所说,.toRad()不是本机函数。为了将来参考,您应该使用Web控制台,它会让您知道错误是什么。在这种情况下,您得到:

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