0

I am searching to know the concept behind this since last month and till now I got these resources

  1. How do I calculate distance between two latitude-longitude points?
  2. geolib.js
  3. Function to calculate distance between two coordinates shows wrong
  4. Calculate distance, bearing and more between Latitude/Longitude points

But I still can't figure out the right distance between specified coordinates

As an instance, I have two coordinates

Start lat: 26.26594 Start long: 78.2095508 Destination lat: 21.24386 Destination long: 81.611

and I got the result as 655.358 KM, but actually (I had measured it using my bike's odometer) those are just ~3 KM far, then why I am getting this answer.

I had even checked for my implementation on that geolib.js (2nd item I have specified in the list items), it is also showing the same result (655.358).

I can't figure it out

JS

// initialising the distance calculation

function geoLocationInit() {
        $('.fd-loc-err').html(''); // empty the error shown, if there is any already
        $('.fd-dist-rest-user').html('<img src="/images/loader.gif" alt="loading"/>'); // loader
        var options = {timeout:120000};
        if (navigator.geolocation) {
            navigator.geolocation.watchPosition(getLocation, gotError, options);
        }
        else {
            locationError = 'Your Browser does not support geolocation';
            showLocationError(locationError);
        }
    }



//finding the coordinates of user

function getLocation(current) {
        var userLat = current.coords.latitude, userLong = current.coords.longitude;
        var distance = getDistance(userLat, userLong, restLatitude, restLongitude);
        $('.fd-dist-rest-user').html('~' + (distance/1000).toFixed(2) + ' km away'); // fd-dist-rest-user is the <div> tag where i have show the distance calculated
    }


    function toRad(value) {
        return value * Math.PI / 180;
    }


    // calculating distance using Vincenty Formula
    function getDistance(lat1, lon1, lat2, lon2) {
        var a = 6378137, b = 6356752.314245,  f = 1/298.257223563;
        var L = toRad(lon2-lon1);
        var U1 = Math.atan((1-f) * Math.tan(toRad(lat1)));
        var U2 = Math.atan((1-f) * Math.tan(toRad(lat2)));
        var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
        var sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);

        var lambda = L, lambdaP, iterLimit = 100;
        do 
        {
            var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);
            var sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) + (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));
            if (sinSigma==0) return 0;

            var cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;
            var sigma = Math.atan2(sinSigma, cosSigma);
            var sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
            var cosSqAlpha = 1 - sinAlpha*sinAlpha;
            var cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha;
            if (isNaN(cos2SigmaM)) cos2SigmaM = 0;
            var C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
            lambdaP = lambda;
            lambda = L + (1-C) * f * sinAlpha * (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
        } while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0);

        if (iterLimit==0) return NaN

        var uSq = cosSqAlpha * (a*a - b*b) / (b*b);
        var A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
        var B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
        var deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
        var s = b*A*(sigma-deltaSigma);
        return s;
    }


// Error handling for the geolocation

    function gotError(error) {
        switch(error.code) {
            case 1: 
                locationError = 'You need to give the permission to use your location to calculate the distances between this restaurant and you <button class="btn btn-danger fd-detect-lctn-try-agn">Please try again</button>';
                break;
            case 2:
                locationError = 'TIME OUT - You need to give permission to use your location to show the distance of this restaurant from your current position <button class="btn btn-danger fd-detect-lctn-try-agn">Please try again</button>';
                break;
            case 3:
                locationError = 'It took to long getting your position, <button class="btn btn-danger fd-detect-lctn">Please try again</button>';
                break;
            default:
                locationError = 'An unknown error has occurred, <button class="btn btn-danger fd-detect-lctn">Please try again</button>';
        }
        showLocationError(locationError);
    }

    function showLocationError(msg) {
        $('.fd-loc-err').html(msg);
        $('.fd-dist-rest-user').html('');
    }

I am getting the latitude and longitude from my database then calling the geoLocationInit function on a button click (below is the following code)

restLongitude = response['longitude'];
restLatitude = response['latitude'];
geoLocationInit(); /* getting location initialisation */
Cœur
  • 37,241
  • 25
  • 195
  • 267
Aman Singh
  • 743
  • 1
  • 10
  • 20
  • Are you sure your gps coordinates are right? Putting those coordinates into a mapping program like google maps shows those two gps coords quite a distance apart, so your calculation looks correct – Patrick Evans May 29 '15 at 19:03
  • Yes, i am finding those coordinates using HTML5 geolcation API, specified in the function getLocation in my code – Aman Singh May 29 '15 at 19:05
  • What are you using the gelocation api on, desktop browser or mobile device with gps turned on? If either do not have a GPS device geolocation will try to use wifi/internet connection to guess at the GPS location, which isnt very accurate unless the routers are using a gps device and broadcasting. – Patrick Evans May 29 '15 at 19:15
  • @patrick, i am also guessing this as the problem, is there any way to find exact coordinates form the desktop – Aman Singh May 29 '15 at 19:22
  • I believe the only way is to hook up a GPS device – Patrick Evans May 29 '15 at 19:28

2 Answers2

1

After some more research with the help of comments from Patrick Evans, i have found that, i was getting the problem due to lack of gps device on desktops and because of that, the coordinates was not getting accurate which leads to wrong calculation of distances.

According to Firefox - Location Aware Browsing

Accuracy varies greatly from location to location. In some places, our service providers may be able to provide a location to within a few meters. However, in other areas it might be much more than that. All locations returned by our service providers are estimates only and we do not guarantee the accuracy of the locations provided. Please do not use this information for emergencies. Always use common sense.

Source Location-Aware Browsing - How Accurate are the locations

So if one wants to find the almost accurate gps coordinates then one should use either the GPS devices or HTML5 geolocation API in Mobile devices which generally comes with GPS hardware installed, so one will get exact coordinates

Community
  • 1
  • 1
Aman Singh
  • 743
  • 1
  • 10
  • 20
-1

I try to modify the options of the method: 'geoLocationInit' to attempt to access the best possible location, but for this if it is a smart phone should be active wifi and gps.

Would be something like:

var options = {timeout:120000, enableHighAccuracy: true};
Rodrigo Moreno
  • 629
  • 9
  • 24
  • 1
    considering the question, making enableHighAccuracy will not help finding the location even close to accuracy if ip's location is far from the actual location of the desktop – Aman Singh Jun 26 '15 at 18:31