Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rishibarve/b0a5401edc527f0e9ad9571ae0d34e33 to your computer and use it in GitHub Desktop.
Save rishibarve/b0a5401edc527f0e9ad9571ae0d34e33 to your computer and use it in GitHub Desktop.
Big Query STD SQL Gist for Geohash Encode
#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