Skip to main content

Calculate distance between 2 points using MySQL

Lets say you have a customers database and you want to find out how many customers live within 10km radius of your shop, how do you that?

It's easy, provided that you have your customers' address registered in your database. What you need to do is convert that addresses to coordinates and then calculate the distance using haversine formula.

    6371 * ACOS(
        * COS(RADIANS(X(address_location)))
        * COS(RADIANS(Y(address_location)) - RADIANS(:lng))
        + SIN(RADIANS(:lat))
        * SIN(RADIANS(X(address_location)))
) AS distanceInKM
FROM customers
HAVING distanceInKM <= 10;
Replace 6371 to 3959 if you want distance in miles.


Popular posts from this blog