Search code examples
mysqlsqlgeolocation

MySQL select rows in Geolocation range


Background information: I am making an app(school project) where users can search for an item nearby. My app uses a table of Items where all item data is stored.

I need to get the rows which are in a certain diameter(5km) of my user's current position(51.337036, 4.645095). In the Items table there is column for latitude and longitude to locate the item.

In my current query I can select the rows which are in a square(4 coordinate points) but I need to have a sphere:

WHERE (C.latitude BETWEEN 50 AND 52) AND (C.longitude BETWEEN 3 AND 5)

Is it possible to use a MySQL Geolocation variable or function?

After some research I saw a type POINT, but my table doesn't have that type (the table needs to stay the same).


Solution

  • AS is said in the comment you have to have a point of valid origin

    WHERE st_distance_sphere(POINT(-82.337036, 29.645095 ), POINT(C.`longitude`, C.`latitude` ))/1000 <= 2  AND T.difficulty = 1 AND T.terrain = 2;
    

    This would give you all rows that are in max 2 km disance from POINT(-82.337036, 29.645095 )

    The you have to put your own location