You are very close. Your (otherwise grossly incorrect) distance formula contains the seed of your frame check.
try it
SET @distance_unit := 69.0; SET @radius := 1.0; SET @center_lat := target_latitude_in_degrees; SET @center_lon := target_longitude_in_degrees; SELECT gt.tree_geotags_id, gt.latitude_dl, gt.longitude_dl FROM tree_geotags_t gt WHERE gt.latitude_dl BETWEEN @center_lat - (@radius/@distance_unit) AND @center_lat + (@radius/@distance_unit) AND gt.longitude_dl BETWEEN @center_lon - (@radius / (@distance_unit * COS(RADIANS(@center_lat)))) AND @center_lon + (@radius / (@distance_unit * COS(RADIANS(@center_lat))))
Suppose you know the eastern, western, northern, and southern borders of your bounding box instead of your center. This is an easy adaptation of the above code.
SELECT gt.tree_geotags_id, gt.latitude_dl, gt.longitude_dl FROM tree_geotags_t gt WHERE gt.latitude_dl BETWEEN @east AND @west AND gt.longitude_dl BETWEEN @south AND @north
The question of how to draw the sides of your bounding box from its corners is trivial, as long as the coordinates of the bounding box are in degrees. If they are given in some projection units (for example, the transverse coordinate of the UTM ), then there is no answer that the answer will be placed in the message.
This query can be quickly executed using a composite index on (latitude_dl, longitude_dl, tree_geotags_id) . A latitude search will use the index range scan, and longitude and identifier can be obtained directly from the index.
What happened to the distance formula? This is Cartesian, but you need the formula of the spherical cosine law, because you are dealing with spherical coordinates.
This will not work close to the north or south pole (because cos (latitude) tends to zero there), but this is normal; you are dealing with trees, and they are not growing there yet.
Here you will find an exhaustive entry on this topic. http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/