What's Needed?
I want to get all the restaurants that are near the user's current location (10KM in range).
Description
I have a users table user(Id, Name, Address)
, here the address is a lat, long
string. e.g. 20,21
.
2nd table is restaurant(Id, Name, Address)
, and the format for address is the same as above.
On the front-end I get the current location of the user, and send to the API, and in the API I have a function calling below query from MySQL:
const getAllRestaurants = async (currentAddress: string): Promise<Array<Restaurant>> => {
// query restaurants (using typeorm which will generate something like this)
const rests = "SELECT * FROM restaurant LIMIT 0, 10";
const restsToReturn = [];
// got the restaurants, now filter on based of address
for (const rest of rests) {
// call "isRestaurantInRange" which will return true if the restaurant is user's range
if (isRestaurantInRange(rest.Address, currentAddress)) {
restsToReturn.push(rest);
}
}
return restsToReturn;
}
Drawbacks:
- It's SLOW.
- The pagination doesn't work as expected, because if 2 out of 10 are in the user's range then we have to manually load up the next data and check the same condition until it reaches 10.
- It's a DIRTY way to approach it.
What I am expecting:
Can
isRestaurantInRange
saved in database (MySQL)? So that when I request the function runs on the database level and return the expected results, without manually filtering it? I am not a MySQL expert, but stored procedure will NOT work as far as I know. Although, there's a caveat with this approach. i.e. I can't call Google Maps Distance API to have exact distance between two points, so need a solution which have google API working.If you know a TypeORM based solution, it would also be acceptable.