Last active
May 27, 2020 12:42
-
-
Save killerbees/671ac912e22a8383e109beacc1904f1a to your computer and use it in GitHub Desktop.
Big Query STD SQL Gist for Geohash Encode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#standardSQL | |
CREATE TEMPORARY FUNCTION geohashEncode(latitude FLOAT64, logitude FLOAT64, precision FLOAT64) | |
RETURNS STRING | |
LANGUAGE js | |
AS """ | |
var Geohash = {}; | |
/* (Geohash-specific) Base32 map */ | |
Geohash.base32 = '0123456789bcdefghjkmnpqrstuvwxyz'; | |
lat = Number(latitude); | |
lon = Number(logitude); | |
precision = Number(precision); | |
if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error('Invalid geohash'); | |
var idx = 0; // index into base32 map | |
var bit = 0; // each char holds 5 bits | |
var evenBit = true; | |
var geohash = ''; | |
var latMin = -90, latMax = 90; | |
var lonMin = -180, lonMax = 180; | |
while (geohash.length < precision) { | |
if (evenBit) { | |
// bisect E-W longitude | |
var lonMid = (lonMin + lonMax) / 2; | |
if (lon >= lonMid) { | |
idx = idx*2 + 1; | |
lonMin = lonMid; | |
} else { | |
idx = idx*2; | |
lonMax = lonMid; | |
} | |
} else { | |
// bisect N-S latitude | |
var latMid = (latMin + latMax) / 2; | |
if (lat >= latMid) { | |
idx = idx*2 + 1; | |
latMin = latMid; | |
} else { | |
idx = idx*2; | |
latMax = latMid; | |
} | |
} | |
evenBit = !evenBit; | |
if (++bit == 5) { | |
// 5 bits gives us a character: append it and start over | |
geohash += Geohash.base32.charAt(idx); | |
bit = 0; | |
idx = 0; | |
} | |
} | |
return geohash; | |
"""; | |
select geohashEncode(38.2842289, -0.5580645, 6); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment