How to Calculate Distance Between Two GPS Coordinates in JavaScript
When working with maps, GPS data, or location-based applications, one of the most common questions is: How far apart are these two coordinates? Suppose we have two locations: Point A Latitude: 40.7128 Longitude: -74.0060 Point B Latitude: 34.0522 Longitude: -118.2437 These are approximately New York City and Los Angeles. We can't simply subtract the latitude and longitude values and treat them like normal Cartesian coordinates. The Earth is curved. For many web applications, a practical solution is the Haversine formula, which calculates the great-circle distance between two points on a sphere. In this article, we'll build a reusable JavaScript implementation that supports: Latitude and longitude validation Degrees-to-radians conversion The Haversine formula Kilometers Miles Nautical miles TypeScript Unit tests Real-world coordinate testing Why Simple Euclidean Distance Doesn't Work If we had two points on a flat coordinate plane: (x1, y1) (x2, y2) we could use: distance = √((x2 - x1)² + (y2 - y1)²) Latitude and longitude don't work like that. They represent positions on the Earth's surface. A degree of longitude also does not represent the same physical distance everywhere. Near the Equator, one degree of longitude covers a much larger distance than it does near the poles. So this: const distance = Math.sqrt( (lat2 - lat1) ** 2 + (lon2 - lon1) ** 2 ); does not give us a meaningful distance in kilometers or miles. We need to account for the Earth's curvature. The Haversine Formula The Haversine formula estimates the great-circle distance between two points using their latitude and longitude. The main idea is: Latitude / Longitude ↓ Convert degrees to radians ↓ Calculate angular distance ↓ Multiply by Earth's radius ↓ Physical distance We'll break the implementation into small pieces. Convert Degrees to Radians JavaScript's trigonometric functions such as: Math.sin() Math.cos() Math.atan2() expect radians rather than degrees. So we first need a helper: function toRadians(degrees) { return degrees * Math.PI / 180; } For example: console.log(toRadians(180)); returns approximately: 3.141592653589793 which is π radians. A Basic Distance Function Let's start with a simple Haversine implementation: function distanceBetweenCoordinates( lat1, lon1, lat2, lon2 ) { const earthRadiusKm = 6371.0088; const dLat = toRadians(lat2 - lat1); const dLon = toRadians(lon2 - lon1); const latitude1 = toRadians(lat1); const latitude2 = toRadians(lat2); const a = Math.sin(dLat / 2) ** 2 + Math.cos(latitude1) * Math.cos(latitude2) * Math.sin(dLon / 2) ** 2; const c = 2 * Math.atan2( Math.sqrt(a), Math.sqrt(1 - a) ); return earthRadiusKm * c; } Usage: const distance = distanceBetweenCoordinates( 40.7128, -74.0060, 34.0522, -118.2437 ); console.log(distance); The result is approximately: 3935 km depending on the Earth radius and rounding you use. What Is Happening Inside the Formula? Let's break the calculation down. First, calculate the differences: const dLat = toRadians(lat2 - lat1); const dLon = toRadians(lon2 - lon1); Then convert both latitude values to radians: const latitude1 = toRadians(lat1); const latitude2 = toRadians(lat2); Next: const a = Math.sin(dLat / 2) ** 2 + Math.cos(latitude1) * Math.cos(latitude2) * Math.sin(dLon / 2) ** 2; This gives us an intermediate value representing the angular relationship between the two points. Then: const c = 2 * Math.atan2( Math.sqrt(a), Math.sqrt(1 - a) ); produces the central angle between the locations. Finally: earthRadiusKm * c converts that angular distance into kilometers. Validate Latitude and Longitude Before calculating distance, we should validate the inputs. Latitude must be between: -90 and 90 Longitude must be between: -180 and 180 Let's create reusable validators: function isValidLatitude(value) { return ( Number.isFinite(value) && value >= -90 && value = -180 && value
This is a summary aggregated from Dev.to. Read the complete article on the original site:
Read full article at Dev.to