HTML坐标距离计算器无法打印

时间:2015-06-28 00:09:06

标签: javascript html geolocation coordinates document.write

我一直在使用Haversine公式处理这个HTML / Javascript代码,以便告诉两个设备之间的距离。它目前尚未完成,但代码应该是可读的。出于某种原因" d"计算后,距离的最终变量是不打印(document.write)。该网站目前在http://magebattle.netau.net/托管,但为了使这篇文章更加干净,请在那里查看源代码,而不是将其全部放在这里。 (抱歉缩进) 相关的JS:

            // Wait for device API libraries to load
            //
            document.addEventListener("deviceready", onDeviceReady, false);
            // device APIs are available
            //
            function onDeviceReady() {
                navigator.geolocation.getCurrentPosition(onSuccess, onError);
            }
            // onSuccess Geolocation
            //
            function onSuccess(position) {
                var lat2 = position.coords.latitude             
                            var lon2 = position.coords.longitude
                            var lat1 = 42.806911; 
            var lon1 = -71.290611; 
            var R = 6371; // km 
            //has a problem with the .toRad() method below.
            var x1 = lat2-lat1;
            var dLat = x1.toRad();  
            var x2 = lon2-lon1;
            var dLon = x2.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; 
            document.write(d);
            }

            // onError Callback receives a PositionError object
            //
            function onError(error) {
                alert('code: '    + error.code    + '\n' +
                    'message: ' + error.message + '\n');
            }
        Number.prototype.toRad = function() {
                    return this * Math.PI / 180;
        }           

1 个答案:

答案 0 :(得分:0)

该函数很好,如果你调用它可以给出结果。设备似乎没有触发,您是否尝试使用移动设备?