Search code examples
mysqlgeometrygeolocationgeospatialspatial

MySQL Distance Between Point and Circle


My aim is to calculate the minimum distance between a point and a circle (defined by a point and a radius). This problem is also definde a shortest distance between a point and a circle.

Also described as 'D' at the image:

Distance calculation

First off the bat, i worked on distance between two points and got this query working as intended.

select st_distance_sphere(
POINT(-27.3449,33.7501), 
POINT( 22.6761,45.7442)
) 

This returns me distance between these two points. But i want to calculate distance between a point and a circle. Parameters I have is:

point1_lat, point1_long, point2_lat, point2_long, point2_radius (in meters)

Is there a magic function for this in MySQL or should i resort to manual calculation using mathematical means.

Every opinion counts. Thank you


Solution

  • I think something as simple as

    GREATEST(st_distance_sphere(circle_center, point) - circle_radius, 0)

    should work.

    This computes distance between center of the circle and the point, the minimum distance between circle and point is less by circle_radius. We then make sure it is non-negative (if the point is within circle).