0

I am trying to create a script where people can input latitude and longitude to show the nearest place from places table. Using "like" or "=" will show fetch the results with exact match. But I want to be able show the nearest place if there is no exact match. Is there is any way to calculate distance in MySQL? Please Help. Thanks

Ramen Bar
  • 61
  • 3

1 Answers1

1

You can use The Vincenty Formula https://en.wikipedia.org/wiki/Vincenty%27s_formulae .

In MySql you can create a function to calculate distance with this code:

DELIMITER $$
DROP FUNCTION IF EXISTS vincenty_distance$$
CREATE FUNCTION vincenty_distance(lat1 DOUBLE, lon1 DOUBLE, lat2 DOUBLE, lon2 DOUBLE) RETURNS DOUBLE
BEGIN
    DECLARE TO_RAD DOUBLE;
    DECLARE a INT;
    DECLARE b DOUBLE;
    DECLARE f DOUBLE;
    DECLARE L DOUBLE;
    DECLARE U1 DOUBLE;
    DECLARE U2 DOUBLE;
    DECLARE sinU1 DOUBLE;
    DECLARE cosU1 DOUBLE;
    DECLARE sinU2 DOUBLE;
    DECLARE cosU2 DOUBLE;
    DECLARE lambda DOUBLE;
    DECLARE lambdaP DOUBLE;
    DECLARE iterLimit INT;
    DECLARE sinLambda DOUBLE;
    DECLARE cosLambda DOUBLE;
    DECLARE sinSigma DOUBLE;
    DECLARE cosSigma DOUBLE;
    DECLARE sigma DOUBLE;
    DECLARE sinAlpha DOUBLE;
    DECLARE cosSqAlpha DOUBLE;
    DECLARE cos2SigmaM DOUBLE;
    DECLARE C DOUBLE;
    DECLARE D DOUBLE;
    DECLARE E DOUBLE;
    DECLARE uSq DOUBLE;
    DECLARE deltaSigma DOUBLE;
    DECLARE s DOUBLE;
    SET TO_RAD = pi() / 180; /*converts degree to raians*/
    SET a = 6378137;
    SET b = 6356752.3142;
    SET f = 1 / 298.257223563; /* WGS-84 ellipsoid params*/
    SET L = (lon2-lon1) * TO_RAD;
    SET U1 = atan((1 - f) * tan(lat1 * TO_RAD));
    SET U2 = atan((1 - f) * tan(lat2 * TO_RAD));
    SET sinU1 = sin(U1);
    SET cosU1 = cos(U1);
    SET sinU2 = sin(U2);
    SET cosU2 = cos(U2);
    SET lambda = L;
    SET iterLimit = 100;
    REPEAT
        SET sinLambda = sin(lambda);
        SET cosLambda = cos(lambda);
        SET sinSigma = sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda) + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda));

        IF 0 = sinSigma THEN
            RETURN 0; /* co-incident points*/
        END IF;
        SET cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
        SET sigma = atan2(sinSigma, cosSigma);
        SET sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
        SET cosSqAlpha = 1 - sinAlpha * sinAlpha;
        IF (cosSqAlpha = 0) THEN
           SET cos2SigmaM = 0; /* equatorial line: cosSqAlpha = 0 (§6)*/
        ELSE
            SET cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
            SET C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
        END IF;
        SET lambdaP = lambda;
        SET lambda = L + (1 - C) * f * sinAlpha * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
        SET iterLimit = iterLimit - 1;
    UNTIL (abs(lambda - lambdaP) <= 0.0000000001 && iterLimit = 0) END REPEAT;
    SET uSq = cosSqAlpha * (a * a - b * b) / (b * b);
    SET D = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
    SET E = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
    SET deltaSigma = E * sinSigma * (cos2SigmaM + E / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - E / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
    SET s = b * D * (sigma - deltaSigma);

    RETURN round(s, 3); /* round to 1mm precision*/
END$$
DELIMITER ;

To use, you simply need to call function vincenty_distance with latitude and longitude parameters, example:

SELECT vincenty_distance(47.6593,10.97647,46.2512010,10.069972);

The Vincenty Formula is one of most precise methods to calculate distance because it assumes the figure of earth as an oblate spheroid.

The Alghorithm returns a distance in meters with a precision of 1mm.

Otherwise if you prefer a faster but inaccurate calculation (valid only on small distance), you an use pythagorean theorem: Calculating distance (pythagoras) and running count in sql query

There are lots of other formulas to calculate distance, you need to choose one according to accuracy and performance you need:

https://en.wikipedia.org/wiki/Geographical_distance

MySQL Great Circle Distance (Haversine formula)

Stefano Balzarotti
  • 1,760
  • 1
  • 18
  • 35
  • There is an error: `[ERROR in query 2] This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)`. I used this exactly same function before in my previous server without problem. Now when i want to migrate to Amazon RDS, that error appear – HendraWD Feb 21 '18 at 12:39
  • Looks like Amazon RDS is strict about this. I am able to solved it by creating new `Parameter Groups` and set `log_bin_trust_function_creators` value to 1. Then I set my MySQL RDS instance to use the newly created parameter group, reboot it, and rerun this query -_- – HendraWD Feb 21 '18 at 13:06