Calculate distance between two GPS coordinates
This code sample will allow you to calculate the distance between two points (GPS coordinates).
function calcLatLonDistance(lat1, lon1, lat2, lon2) { if (!lat1 || !lat2 || !lon1 || !lon2) { return; } if (typeof (Number.prototype.toRadians) === "undefined") { Number.prototype.toRadians = function () { return this * Math.PI / 180; }; } var R = 6371; // km var φ1 = lat1.toRadians(); var φ2 = lat2.toRadians(); var Δφ = (lat2 - lat1).toRadians(); var Δλ = (lon2 - lon1).toRadians(); var a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return parseInt(d * 0.621371); }
Directions:
- call calcLatLonDistance(lat1, lon1, lat2, lon2);
Note:
This snippet focuses on iOS development. Make sure to verify/adapt any vendor prefixes. Back to main listing.
Published: Sun, Jan 10 2016 @ 18:52:37
Back to Blog