Search code examples
phplaravelgeolocatione-commercelatitude-longitude

Find location registered in database by the given longitude and latitude - Laravel


I'm working on an e-commerce, and I encountered an problem understanding the way to find a location by the given (longitude - latitude) and get the matched location from locations table in the database.

I have locations table to store all my country's cities there.

Ex:

city_name fee lng lat
Babil. 12 47.0983 31.90043
Baghdad. 5 47.0983 31.90043
............ ... ....... ......

the above lng & lat are fake.

What I want is:

when a user select his location on the maps from the mobile app, the app sends his selected location's (longitude - latitude) through the API endpoint:

e.g. /locations?lng=xxx&lat=xxx

then the server (Laravel App) should check the (lng-lat) with the locations table to find user's city according to the given creds.

sorry if I couldn't explain well but this is how it should be, not check for the nearest location or something like that.


Solution

  • From your explanation what i can understand is that you want to find cities nearest to user position. You can use distance farmula here that is

    =ACOS( SIN(lat1 * PI()/180) * SIN(lat2 * PI()/180) + COS(lat1 * PI()/180) * COS(lat2 * PI()/180) * COS(lon2 * PI()/180-lon1 * PI()/180) ) * 6371000

    You can use this formula to convert lat, lng into distance and then can sort your data according to distance.

    Or if you want to just query data according to given lat, lng then you can simply run select query on your table. One thing to make sure is that you must store lat,lng with 8 decimal places to find accurate result.