I am developing an app which calculate the distance between 2 points. I cannot use the Google Maps API.
I have found the coordinates for each of the markers in the map below.
I am then using the haversine formula to calculate the distance between each points.
e.g. 1 -> 2, 2 -> 3, 3 -> 4... etc up to the final point.
I add up these distances to retrieve the total distance for the route.
The problem is Google maps says it is 950-1000 meters, but my app says the length is 1150-1200 meters. I have tried adding in more coordinates, removing coordinates, but I am still getting approximately 200 meters longer route.
Out of curiosity I calculated the distance between the start and end point (the 2 green stars) and this matched the Google Maps distance (998 metres to be exact).
Does this mean Google Maps calculates its distances without the consideration of roads / paths etc.
Here is my code:
var coordinates = [
[1,51.465097,-3.170893,1,0],
[2,51.465526,-3.170714,0,0],
[3,51.465853,-3.170526,0,0],
[4,51.466168,-3.170338,0,0],
[5,51.466305,-3.170236,0,0],
[6,51.466534,-3.170157,0,0],
[7,51.466798,-3.170159,0,0],
[8,51.467042,-3.170232,0,0],
[9,51.467506,-3.170580,0,0],
[10,51.468076,-3.171532,0,0],
[11,51.468863,-3.172170,0,0],
[12,51.469284,-3.172841,0,0],
[13,51.469910,-3.174732,0,0],
[14,51.470037,-3.174930,0,0],
[15,51.470350,-3.175091,0,0],
[16,51.472447,-3.176151,1,0]
];
function distanceBetweenCoordinates() //calculates the distance between each of the coordinates
{
for (var i=0; i<coordinates.length-1; i++)
{
var firstClosestPoint = [0,0,6371];
var secondClosestPoint = [0,0,6371];
var lng1 = (coordinates[i][1]);
var lat1 = (coordinates[i][2]);
var lng2 = (coordinates[i+1][2]);
var lat2 = (coordinates[i+1][2]);
var d = haversine(lat1, lng1, lat2, lng2);
routeLength = routeLength + d;
}
return distanceBetweenCoordinatesArray; //returns the array which stores the 2 points and the distance between the 2 points
}
EDIT
Here is my haversine forumla to calculate the distance between 2 points:
Source: here
Number.prototype.toRad = function() //to rad function which is used by the haversine formula
{
return this * Math.PI / 180;
}
function haversine(lat1, lng1, lat2, lng2) { //haversine foruma which is used to calculate the distance between 2 coordinates
lon1 = lng1;
lon2 = lng2;
var R = 6371000; // metres
var a = lat1.toRad();
var b = lat2.toRad();
var c = (lat2-lat1).toRad();
var d = (lon2-lon1).toRad();
var a = Math.sin(c/2) * Math.sin(c/2) +
Math.cos(a) * Math.cos(b) *
Math.sin(d/2) * Math.sin(d/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
See Question&Answers more detail:
os