Calculating Distances Between Geographic Points with MySQL 5.7
MySQL 5.7 provides the STDistanceSphere function for calculating the great-circle distance between two geographic points.
MySQL 5.7 provides the ST_Distance_Sphere function for calculating the great-circle distance between two geographic points.
The arguments for the ST_Distance_Sphere function should follow the order of longitude first, then latitude.
Short Distance Example
Here, we calculate the distance between two points in Osaka.
SELECT ST_Distance_Sphere( GeomFromText('POINT(135.507260 34.693946)'), GeomFromText('POINT(135.526201 34.687316)') ) AS distance_meterFROM dual;| row | distance_meter |
|---|---|
| 1 | 1882.1360099034516 |

Long Distance Example
For longer distances, let’s calculate the distance between JR Osaka Station and JR Tokyo Station.
SELECT ST_Distance_Sphere( GeomFromText('POINT(135.495951 34.702488)'), -- JR Osaka station GeomFromText('POINT(139.767052 35.681168)') -- JR Tokyo station ) AS distance_meterFROM dual;| row | distance_meter |
|---|---|
| 1 | 403048.2752256764 |

Near the Poles Example
To demonstrate the accuracy near the poles, let’s measure a distance at Svalbard, a high-latitude region.
SELECT ST_Distance_Sphere( GeomFromText('POINT(16.379258 78.655621)'), -- Pyramiden Container Hostel GeomFromText('POINT(16.328528 78.655143)') -- Hotel Tulpan ) AS distance_meterFROM dual;| row | distance_meter |
|---|---|
| 1 | 1110.8932928975748 |

Benefits of MySQL Spatial Functions
Using MySQL’s spatial analysis functions, developers can easily implement robust geographic data processing capabilities. These functions are highly optimized for performance and accuracy, making them ideal for applications requiring geographic calculations.
Related posts
Querying Amazon Neptune with Gremlin
This note shows how to query Amazon Neptune graph data using Gremlin.
Searching Across Multiple Elasticsearch Indices
This note describes how to search over multiple indices in Elasticsearch.
Sign in with Slack Using Cognito User Pools and OIDC
This note describes how to federate Cognito user pools with Slack using OIDC to implement "Sign in with Slack".
Deploying FastAPI on AWS Lambda with Lambda Web Adapter
This example guides you through the process of developing API backends with FastAPI using Lambda Web Adapter.
API Gateway WebSocket: Implementing a Mock Integration
This note describes how to build an API Gateway WebSocket endpoint using mock integration.
