本文介绍了toRad()Javascript函数抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在尝试使用此处描述的技术在计算两个纬度 - 经度点之间的距离? (Haversine公式) 代码如下 Javascript: var R = 6371; //以公里为单位的地球半径 var dLat =(lat2-lat1).toRad(); //以弧度表示的Javascript函数 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)); var d = R * c; //以km为单位的距离b $ b 但是当我尝试实现它时,出现错误 Uncaught TypeError:Object 20 has no Method'toRad'。 我需要一个特殊的库或其他东西来获取.toRad )工作?因为它似乎是搞砸了第二行。解决方案你缺少函数声明。 p> 在这种情况下 toRad()必须先定义为: / **将数值度数转换为弧度* / if(typeof(Number.prototype.toRad)===undefined){ Number.prototype.toRad = function(){ return this * Math.PI / 180; } 根据代码段全部在页面底部 I'm trying to find the distance between two points (for which I've latitudes & longitudes) using the technique described here at Calculate distance between two latitude-longitude points? (Haversine formula)The codes are as belowJavascript:var R = 6371; // Radius of the earth in kmvar dLat = (lat2-lat1).toRad(); // Javascript functions in radiansvar 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));var d = R * c; // Distance in kmBut when I try to implement it, an error shows up saying Uncaught TypeError: Object 20 has no Method 'toRad'.Do I need a special library or something to get .toRad() working? because it seems to bescrewing up on the second line. 解决方案 You are missing a function declaration.In this case toRad() must be defined first as:/** Converts numeric degrees to radians */if (typeof(Number.prototype.toRad) === "undefined") { Number.prototype.toRad = function() { return this * Math.PI / 180; }}according to the code segment all at the bottom of the page 这篇关于toRad()Javascript函数抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-20 10:37