Calculate Distance Using Latitude and Longitude in MySQL
To calculate the distance between two points specified by their latitude and longitude coordinates in MySQL, you can use the Haversine formula. The Haversine formula calculates the shortest distance between two points on the surface of a sphere given their latitudes and longitudes.
Here’s how you can create a MySQL function to calculate the distance using the Haversine formula:
DELIMITER $$
CREATE FUNCTION distance(lat1 FLOAT, lon1 FLOAT, lat2 FLOAT, lon2 FLOAT) RETURNS FLOAT
BEGIN
DECLARE R FLOAT DEFAULT 6371; -- Earth's radius in kilometers
DECLARE dLat FLOAT;
DECLARE dLon FLOAT;
DECLARE a FLOAT;
DECLARE c FLOAT;
DECLARE d FLOAT;
SET dLat = RADIANS(lat2 - lat1);
SET dLon = RADIANS(lon2 - lon1);
SET a = SIN(dLat / 2) * SIN(dLat / 2) + COS(RADIANS(lat1)) * COS(RADIANS(lat2)) * SIN(dLon / 2) * SIN(dLon / 2);
SET c = 2 * ATAN2(SQRT(a), SQRT(1 - a));
SET d = R * c;
RETURN d;
END$$
DELIMITER ;
This function takes four parameters: the latitude and longitude of the first point (lat1, lon1), and the latitude and longitude of the second point (lat2, lon2). It calculates the distance between these two points using the Haversine formula and returns the distance in kilometers.
You can then use this function in your SQL queries to calculate the distance between points. For example:
SELECT distance(40.7128, -74.0060, 34.0522, -118.2437) AS distance_between_points;
This query will calculate the distance between New York City (latitude 40.7128, longitude -74.0060) and Los Angeles (latitude 34.0522, longitude -118.2437) in kilometers.