NativeScript / nativescript-geolocation

Geolocation plugin to use for getting current location, monitor movement, etc
Apache License 2.0
139 stars 77 forks source link

Distance function returns 0 between two locations #260

Open thamibn opened 4 years ago

thamibn commented 4 years ago

Hi,

When i use two locations taken from google maps to calculate distance it always give me 0, not sure why

here is my code example

// -26.275406, 27.811755 from google maps
      let thisLocation = new geolocation.Location();
      thisLocation.latitude = "-26.275406";
      thisLocation.longitude = "27.811755";

      //  -26.281879, 27.772300 from google maps
      let myLocation = new geolocation.Location();
      myLocation.latitude = "-26.281879";
      myLocation.longitude = "27.772300";

      let dist = Math.floor(geolocation.distance(myLocation, thisLocation));
      this.locationDistance = `DIstance is ${dist} meters away.`;

i am using nativescript vue testing on my android device

akarsh014 commented 4 years ago

I have faced this issue as well, i get 0 when i calculate the distance.

justinmespel commented 3 years ago

I wasn't getting very accurate distances using this function either. I use this to calculate the distance in KM, then times the result by 1000

calculateKmDistance(loc1, loc2): number {

    const R = 6371.0710; // Radius of the Earth in Km
    const r1 = loc1.latitude * (Math.PI / 180); // Convert degrees to radians
    const r2 = loc2.latitude * (Math.PI / 180); // Convert degrees to radians
    const d1 = r2 - r1; // Radian difference (latitudes)
    const d2 = (loc2.longitude - loc1.longitude) * (Math.PI / 180); // Radian difference (longitudes)

    return 2 * R * Math.asin(Math.sqrt(Math.sin(d1 / 2) *
        Math.sin(d1 / 2) + Math.cos(r1) * Math.cos(r2) *
        Math.sin(d2 / 2) * Math.sin(d2 / 2)));
}
alexonozor commented 1 year ago

Do you still need to times the result by 1000 to get it in KM?

I wasn't getting very accurate distances using this function either. I use this to calculate the distance in KM, then times the result by 1000

calculateKmDistance(loc1, loc2): number {

    const R = 6371.0710; // Radius of the Earth in Km
    const r1 = loc1.latitude * (Math.PI / 180); // Convert degrees to radians
    const r2 = loc2.latitude * (Math.PI / 180); // Convert degrees to radians
    const d1 = r2 - r1; // Radian difference (latitudes)
    const d2 = (loc2.longitude - loc1.longitude) * (Math.PI / 180); // Radian difference (longitudes)

    return 2 * R * Math.asin(Math.sqrt(Math.sin(d1 / 2) *
        Math.sin(d1 / 2) + Math.cos(r1) * Math.cos(r2) *
        Math.sin(d2 / 2) * Math.sin(d2 / 2)));
}
justinmespel commented 1 year ago

@alexonozor I don't think so, it should return the result in KM. I think / 1000 to get it in meters.