Last active
April 29, 2022 00:14
-
-
Save meyer1994/b2820df81eeba7a3ad5a441294d817e6 to your computer and use it in GitHub Desktop.
GeoHash in 100% python
This file contains 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
# Adapted from: | |
# https://mmcloughlin.com/posts/geohash-assembly | |
import math | |
def encode(lat: float, lon: float) -> str: | |
lat = math.floor(2**64 * (lat + 90) / 180) | |
lon = math.floor(2**64 * (lon + 180) / 360) | |
lat = bin(lat)[2:] | |
lon = bin(lon)[2:] | |
geo = ''.join(i + j for i, j in zip(lon, lat)) | |
geo = int(geo, 2) | |
return hex(geo) | |
def decode(geo: str) -> tuple[float, float]: | |
geo = int(geo, 16) | |
geo = bin(geo)[2:] | |
lat = ''.join(geo[1::2]) | |
lon = ''.join(geo[::2]) | |
lat = (int(lat, 2) * 180) / 2**64 - 90 | |
lon = (int(lon, 2) * 360) / 2**64 - 180 | |
return lat, lon | |
lat = 27.988056 | |
lon = 86.925278 | |
geo = encode(lat, lon) | |
print(geo) | |
lat, lon = decode(geo) | |
print(lat, lon) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment