地理定位功能赢得';不行!Javascript

地理定位功能赢得';不行!Javascript,javascript,html,geolocation,Javascript,Html,Geolocation,可能重复: 首先我得到了这两个p标签 <p id="pos"></p> <p id="dist"></p> 我把我的位置放在“pos”,把我和纽约之间的距离放在“dist”。 我有两个按钮来触发JS函数: <button onclick="getLocation()">Get position</button> <button onclick="calcDistance()">Calculate dis

可能重复:

首先我得到了这两个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;   
}
var x=document.getElementById(“pos”);
var d=document.getElementById(“dist”);
var startPos;
函数getLocation(){
navigator.geolocation.getCurrentPosition(函数(位置){
startPos=位置;
x、 innerHTML=“您的职位”+
“纬度:”+startPos.coords.Latitude+
“
经度:”+startPos.coords.Longitude; }); }; 函数calcDistance(){ var distt=计算距离(startPos.coords.latitude,startPos.coords.longitude,40.28371627,-73.994901); d、 innerHTML=distt.toFixed(1); }; 函数CalculateInstance(lat1、lon1、lat2、lon2){ var R=6371; var dLat=(lat2-lat1.toRad(); var dLon=(lon2-lon1.toRad(); 变量a=Math.sin(dLat/2)*Math.sin(dLat/2)+ Math.cos(lat1.toRad())*Math.cos(lat2.toRad())* 数学单(dLon/2)*数学单(dLon/2); var c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a)); 返回R*c; }
我的calcDistance按钮不工作,我不知道问题出在哪里。
我试着在calculateInstance()中输入数字,但仍然不起作用。怎么会呢?

把这个放在你的JS上面:

Number.prototype.toRad = function() {
  return this * Math.PI / 180;
}
正如@apsillers所说,
.toRad()
不是本机函数。作为将来的参考,您应该使用一个web控制台,它会让您知道错误是什么。在这种情况下,您会得到:


Uncaught TypeError:Object-0.123871823没有方法“toRad”

因为
.toRad()
不是数字的数字函数?我们的老师让我们使用这个函数,所以我想我们不会在意它。那为什么toRad会让它不工作呢?你在调用一个不存在的函数。也许你的老师让你使用一个定义了
toRad
的库?或者您的老师希望您使用具有
toRad
功能的语言?或者你的老师只是希望你自己给它下定义。注意到这个问题本质上是一样的:是的,可能会被当作傻瓜关起来。编辑:投票。谢谢!显然,我忘了包含这个
if(typeof(Number.prototype.toRad)==“undefined”){Number.prototype.toRad=function(){returnthis*Math.PI/180;};};}if(typeof(Number.prototype.toDeg)==“undefined”){Number.prototype.toDeg=function(){返回这个*180/Math.PI;};}