We have a MySQL stored procedure that accepts input as latitude and longitude. This stored procedure has to return back the 3 closest area to this lat/long and respective distance in kilometre from the given lat/long.
The area table has id, name, position. The position is of point type having POINT(latitude, longitude). I have tried following solution:
SELECT
id,
name,
X(position) AS 'latitude',
Y(position) AS 'longitude',
(
GLength(
LineStringFromWKB(
LineString(
position,
GeomFromText('POINT(@lat @long)')
)
)
)
)
AS distance
FROM areas
ORDER BY distance ASC
limit 3;
Few issues in the above solution:
- Query is slow. It's taking 200 millisecond for 22k records. If I remove order by clause, performance improves drastically i.e. it takes only 20 milliseconds. I have created spatial index for position column but didn't help. Can someone suggest how to optimize this query?
- I am not sure how to convert this distance in kilometer?