1
votes

I use below two ways to calculate distance between two points in google maps using latitude and longitude.

            TYPE I:
         function CalcDistanceBetween(lat1, lon1, lat2, lon2) {
//Radius of the earth in:  1.609344 miles,  6371 km  | var R = (6371 / 1.609344);
var R = 6371; // Radius of earth in Miles 
var dLat = toRad(lat2-lat1);
var dLon = toRad(lon2-lon1); 
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;
   alert("d==" + d);
return d;
}
  alert(CalcDistanceBetween(13.125511084202,80.029651635576,12.9898593006481,80.2497744326417));
                 function toRad(Value) {
            /** Converts numeric degrees to radians */
         return Value * Math.PI / 180;
         }  

    TYPE II:

            var p1 = new google.maps.LatLng(13.125511084202,80.029651635576);
            var p2 = new google.maps.LatLng(12.9898593006481,80.2497744326417);

            alert(calcDistance(p1, p2));

           //calculates distance between two points in km's
                       function calcDistance(p1, p2){
                return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) /                              
                  1000).toFixed(2);
                }    

Above both types gives 28 kms as distance. But when i check in google maps with same langitude and longitude it returns 36.8 kms. Sample Check in My Code & google maps Shown Below..:enter image description hereenter image description here

enter image description here

Do u suggest me for get accurate results??

2

2 Answers

3
votes

The distance given by Google is from the suggested route. It's not a direct path from point A to point B. The distance you computed is the direct path, which would only be the case if you flew directly from A to B.
If you want to get the result that Google outputs, look here: An elegant way to find shortest and fastest route in Google Maps API v3?

1
votes

Could be i'm completely mistaken :) but it seems your method calculate the real distance between these 2 points and when you route with google it is the distance of the route you take.