地理位置计算距离为0?

时间:2013-03-02 16:05:57

标签: javascript geolocation

我一直在研究这个问题,而且整天都在向我投掷问题。我现在正处于困境中并且不确定下一步该去哪里。我会指出我对Javascript很新,所以它可能是一个noob错误。

无论如何,总体目标是检查用户当前位置,然后检查它们是否在目标坐标的200m半径内。当我输入当前坐标时,它会在OnInterval函数中运行警报,但如果它们在200米半径范围内则不会运行。

有谁知道如何解决这个问题? :X

var userPositionLat;
var userPositionLong;

jQuery(window).ready(function() {  
    initiate_geolocation();
});

function initiate_geolocation() {  
    //navigator.geolocation.getCurrentPosition(handle_geolocation_query,handle_errors);
    // http://www.thedotproduct.org/2010/04/example-of-navigator-geolocation-watchposition/
    navigator.geolocation.watchPosition(handle_geolocation_query,handle_errors, {enableHighAccuracy:true, maximumAge:30000});
}

function handle_errors(error) {  
    switch(error.code)  
    {  
        case error.PERMISSION_DENIED: alert("user did not share geolocation data");  
        break;

        case error.POSITION_UNAVAILABLE: alert("could not detect current position");  
        break;

        case error.TIMEOUT: alert("retrieving position timed out");  
        break;

        default: alert("unknown error");  
        break;
    }  
}  



function handle_geolocation_query(position) {
    userPositionLat = position.coords.latitude;
    userPositionLong = position.coords.longitude;

    alert('Your latitude is :'+userPositionLat+' and longitude is '+userPositionLong);

    IsUserNearTarget();
}


function CalculateDistance(lat1, long1, lat2, long2) {
    // Translate to a distance
    var distance =
            Math.sin(lat1 * Math.PI) * Math.sin(lat2 * Math.PI) +
            Math.cos(lat1 * Math.PI) * Math.cos(lat2 * Math.PI) * Math.cos(Math.abs(long1 - long2) * Math.PI);

    // Return the distance in meters
    return Math.acos(distance) * 6370981.162;
}

function IsUserNearTarget()
{
    // The target longitude and latitude
    var targetlong = 0.0; //change this with your coordinates to test
    var targetlat = 0.0; //change this with your coordinates to test

    // Start an interval every 1s
    var OurInterval = setInterval(OnInterval, 1000);

    // Call this on an interval
    function OnInterval() {
        var distance = CalculateDistance(targetlat, targetlong, userPositionLat, userPositionLong);

        // Is it in the right distance? (200m)
        if (distance <= 200) {
            // Stop the interval
            clearInterval(OurInterval);

            alert('TOTALLY WORKS BRO');
        }
    }
}

1 个答案:

答案 0 :(得分:1)

要将度数转换为弧度,请乘以π/180,而不是π