devhausleipzigacademy / camp7-final-project

0 stars 0 forks source link

API Route -- Modify existing endpoint for searching users #27

Open franzwollang opened 1 year ago

franzwollang commented 1 year ago

Modify it from just being based on matching interests to also include location as a search.

Use can use PRISMA "where" clauses to constrain the results to only those that: some_lat < lat < other_lat AND some_long < long < other_long

Calculate desired distance in 1) units of LONG and 2) units of LAT. Use these values from your center point (location) to create a bounding box. Use the bounding box to query users from PRISMA.

Then, before you return the results, filter over the results and calculate the true radial distance between each result and the center point (location) to see if it's actually in the radius or not. FIlter out the results that aren't within the radius.

Haversineformula: | a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
-- | --
c = 2 ⋅ atan2( √a, √(1−a) )
d = R ⋅ c
where | φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km);note that angles need to be in radians to pass to trig functions!
JavaScript: | const R = 6371e3; // metres const φ1 = lat1 * Math.PI/180; // φ, λ in radians const φ2 = lat2 * Math.PI/180; const Δφ = (lat2-lat1) * Math.PI/180; const Δλ = (lon2-lon1) * Math.PI/180;  const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +           Math.cos(φ1) * Math.cos(φ2) *           Math.sin(Δλ/2) * Math.sin(Δλ/2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));  const d = R * c; // in metres

Reference for equation & example code

Return the results (users that are within a certain radius of some location).

franzwollang commented 1 year ago

@ReallyBoard123

You can use this library for the distance calculations: https://github.com/manuelbieh/geolib It has a very convenient function called "isPointWithinRadius".

franzwollang commented 1 year ago

Although, this answer looks like the most comprehensive AND efficient solution: https://stackoverflow.com/a/45950426

I can help you write a port of the code to TypeScript, and help you use raw SQL queries inside of Prisma.