I am currently working on a piece of code that calculates a bounding box for a specific location to search for user profiles within a given radius. The code is mostly functional, but I am encountering a slight distortion in the final values. When I input 50 miles into the function, the resulting points are around 70 miles from the origin instead of the expected 50. I suspect that there might be a slight miscalculation in one of the constant values.
Here are the constants used:
const RAD_CON = Math.PI / 180; // Radian conversion constant
const R_EARTH = 6378; // Earth's radius in kilometers
const KM_PER_MILE = 1.609344; // Kilometers per mile conversion constant
// Potential error here
const METER_DEGREES = (1 / ((2 * Math.PI / 360) * R_EARTH)) / 1000; // Meters per degree for latitude and longitude
The problematic code section:
_getBoundingCoords(location: Location, miles: number) {
const meters = miles * KM_PER_MILE * 1000;
const latNorth = location.lat + (meters * METER_DEGREES);
const latSouth = location.lat - (meters * METER_DEGREES);
const lngWest = location.lng + (meters * METER_DEGREES) / Math.cos(location.lat * RAD_CON);
const lngEast = location.lng - (meters * METER_DEGREES) / Math.cos(location.lat * RAD_CON);
return [latNorth, latSouth, lngWest, lngEast];
}
For context, I am using the output values to construct a query for a mongodb collection. The data in the collection is structured as follows:
{
lat: number;
lng: number;
}
The constructed query:
const query = {
$and: [{
'location.lat': {
$lte: latNorth,
$gte: latSouth,
},
}, {
'location.lng': {
$lte: lngWest,
$gte: lngEast,
},
}],
};