Distance between Two Points with MySQL 5.7
MySQL 5.7 offers ST_Distance_Sphere
function to get accurate distance between two points.
Example 1
SQL
SELECT
ST_Distance_Sphere(
GeomFromText('POINT(135.507260 34.693946)'),
GeomFromText('POINT(135.526201 34.687316)')
) AS distance_meter
FROM
dual;
Result
row | distance_meter |
---|---|
1 | 1882.1360099034516 |
Google Map Result
Example 2
You might assume that the distance calculation is accurate just because the two points are close to each other. Let’s measure a longer distance.
SQL
SELECT
ST_Distance_Sphere(
GeomFromText('POINT(135.495951 34.702488)'), -- JR Osaka station
GeomFromText('POINT(139.767052 35.681168)') -- JR Tokyo station
) AS distance_meter
FROM
dual;
Result
row | distance_meter |
---|---|
1 | 403048.2752256764 |
Google Map Result
Example 3
You may think that the second result was just correct because the two points were not near North or South Pole. Let’s measure at Svalbard.
SQL
SELECT
ST_Distance_Sphere(
GeomFromText('POINT(16.379258 78.655621)'), -- Pyramiden Container Hostel
GeomFromText('POINT(16.328528 78.655143)') -- Hotel Tulpan
) AS distance_meter
FROM
dual;
Result
row | distance_meter |
---|---|
1 | 1110.8932928975748 |
Google Map Result
Conclusion
Using MySQL spatial analysis functions, engineers can develop easily applications to handle spatial data.
I hope you will find this post useful.