【问题标题】:Geolocation function won't work! Javascript [duplicate]地理定位功能不起作用! Javascript [重复]
【发布时间】:2012-11-14 05:09:26
【问题描述】:

可能重复:
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() 中输入数字,但它仍然不起作用。怎么会?

【问题讨论】:

  • 因为.toRad()不是数字的数函数?
  • 我们的老师让我们使用这个功能,所以我以为我们不会关心它。那么为什么 toRad 让它不起作用呢?
  • 您正在调用一个不存在的函数。也许您的老师要求您使用定义了toRad 的库?或者您的老师可能希望您使用具有toRad 功能的语言?或者你的老师只是希望你自己定义它。

标签: javascript html geolocation


【解决方案1】:

把这个放在你的 JS 上面:

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

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

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

【讨论】:

  • 注意到了这个基本相同的问题:stackoverflow.com/questions/5260423/…
  • 是的,可能会被当作骗子关闭。编辑:投票。
  • 谢谢!显然,我忘了包括这个if (typeof(Number.prototype.toRad) === "undefined") { Number.prototype.toRad = function() { return this * Math.PI / 180; }; } if (typeof(Number.prototype.toDeg) === "undefined") { Number.prototype.toDeg = function() { return this * 180 / Math.PI; }; }
猜你喜欢
  • 2019-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-26
  • 2013-02-18
相关资源
最近更新 更多