I’m using Javascript for a cross platform app (using Devextreme as developing tool, it is based on PhoneGap) and I need to read the GPS position and compare it with another fixed point. Here how to do it.

This code retrieve the geolocatin information from your device (with GPS if available or with WiFi). Then, it calculates the distance from a fixed point and compare the result with the accuracy of the coordinates. If it is lower, it shows ok (in production: it does the needed stuff) otherwise, it stops showing a message.

Number.prototype.toRadians = function () {
    return this * Math.PI / 180;
}
function onSuccess(position) {
    var R = 6371e3; // metres
    var lat1 = position.coords.latitude;
    var lon1 = position.coords.longitude;
    alert("lat : " + lat1 + " lng : " + lon1);
    var lat2 = 44.980299;
    var lon2 = 7.376744;
    var φ1 = lat1.toRadians();
    var φ2 = lat2.toRadians();
    var Δφ = (lat2 - lat1).toRadians();
    var Δλ = (lon2 - lon1).toRadians();
    var Δψ = Math.log(Math.tan(Math.PI/4+φ2/2)/Math.tan(Math.PI/4+φ1/2));
    var q = Math.abs(Δψ) > 10e-12 ? Δφ/Δψ : Math.cos(φ1); // E-W course becomes ill-conditioned with 0/0
    // if dLon over 180° take shorter rhumb line across the anti-meridian:
    if (Math.abs(Δλ) > Math.PI) Δλ = Δλ>0 ? -(2*Math.PI-Δλ) : (2*Math.PI+Δλ);
    var dist = Math.sqrt(Δφ*Δφ + q*q*Δλ*Δλ) * R;
    alert("Distance in metres from the fixed point [as the crow flies] : " + dist);
    var accuracy = position.coords.accuracy; //precision in metres
    alert("accuracy " + accuracy);
    if (dist <= accuracy)
        alert("ok");
    else
        alert("too far from the fixed point");
}

function onError(error) {
    alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}

var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
};

function onClickgps(e) {
    navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
}
Advertisements