I have created the following MySQL table to store latitude/longitude coordinates along with a name for each point:
CREATE TABLE `points` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`location` point NOT NULL,
PRIMARY KEY (`id`),
SPATIAL KEY `location` (`location`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
I am trying to query:
- all points within an n mile radius of a given point;
- the distance of each returned point from the given point
All of the examples I have found refer to using a minimum bounding rectangle (MBR) rather than a radius. The table contains approximately 1 million points, so this need needs to be as efficient as possible.
I did that for one point inside the circle with radius
details and one more sample query here http://dexxtr.com/post/83498801191/how-to-determine-point-inside-circle-using-mysql, hope this helps
For MySQL 5.7+
Given we have the following simple table,
With the following simple data,
You would get the points within a given range of another point (note: we have to search inside a polygon) with the following combination of st functions:
You should see something like this as a result:
For reference on distance, if we remove the constraint the result for the test point looks like this:
Note 1: the field is called lnglat since that's the correct order if you think of points as (x, y) and is also the order most functions (like point) accept the parameter
Note 2: you can't actually take advantage of spatial indexes if you were to use circles; also note that the point field can be set to accept null but spatial indexes can't index it if it's nullable (all fields in the index are required to be non-null).
Note 3: st_buffer is considered (by the documentation) to be bad for this use case
Note 4: the functions above (in particular st_distance_sphere) are documented as fast but not necessarily super accurate; if your data is super sensitive to that add a bit of wiggle room to the search and do some fine tuning to the result set
Radius is not efficiently indexable. You should use the bounding rectangle to quickly get the points you are probably looking for, and then filter points outside of the radius.
Thank you both for your answers.
I eventually found the solution at http://www.movable-type.co.uk/scripts/latlong-db.html.