Skip to content

Instantly share code, notes, and snippets.

@junaidpv
Created September 16, 2011 10:58
Show Gist options
  • Save junaidpv/1221854 to your computer and use it in GitHub Desktop.
Save junaidpv/1221854 to your computer and use it in GitHub Desktop.
Distance comparison of geolocations with a location given.
SET @c1 = PI()/180,
@c2 = PI()/360,
@r = 6378137,
@lat1 = ?,
@lng1 = ?;
SELECT latitude, longitude, distance
FROM (
SELECT *,
@lat2 := latitude,
@lng2 := longitude,
@dlat := @lat2 - @lat1,
@dlng := @lng2 - @lng1,
@a := (SIN(@dlat * @c2) * SIN(@dlat * @c2)
+ COS(@lat1 * @c1) * COS(@lat2 * @c1) * SIN(@dlng * @c2) * SIN(@dlng * @c2)),
@c := 2 * ATAN2(sqrt(@a), SQRT(1 - @a)),
@d := @r * @c as distance
FROM `locations`
) as x
WHERE distance <= ?;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment