Skip to content

Instantly share code, notes, and snippets.

@mtasuandi
Created September 29, 2015 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtasuandi/975a7894fc6b501df1f7 to your computer and use it in GitHub Desktop.
Save mtasuandi/975a7894fc6b501df1f7 to your computer and use it in GitHub Desktop.
MySQL Haversine Formula
/**
* MySQL 5.6 >
* Table structure (id {primary, autoincrement}, name {string}, location{spatial, geometry})
*/
SELECT 3956 * 2 * ASIN(SQRT(POWER(SIN((Y(location) - ABS(14.601343)) * PI()/180 / 2), 2)+ COS(ABS(Y(location)) * PI()/180 ) * COS(ABS(14.601343) * PI()/180) * POWER(SIN((X(location) - 120.972882) * PI()/180 / 2), 2) )) AS distance, name
FROM table
WHERE ST_Within(location, Envelope(LineString(POINT(120.972882-10/ABS(COS(RADIANS(14.601343))*69), 14.601343-(10/69)), POINT(120.972882+10/ABS(COS(RADIANS(14.601343))*69), 14.601343+(10/69)))))
ORDER BY distance
/**
* MySQL 5.6 <
* Implemented in Laravel RAW Query
* Table structure (id {primary, autoincrement}, name {string}, location{spatial, geometry})
* Parameters {$latitude, $longitude, $distance}
*/
\DB::select('SELECT 3959 * ACOS( COS( RADIANS(?) ) * COS( RADIANS( Y(location) ) ) * COS( RADIANS( X(location) ) - RADIANS(?) ) + SIN( RADIANS(?) ) * SIN( RADIANS( Y(location) ) ) ) AS distance, name FROM table HAVING distance < ? ORDER BY distance', [$latitude, $longitude, $latitude, $distance]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment