Skip to content

Instantly share code, notes, and snippets.

@mdornseif
Created May 26, 2013 13:40
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mdornseif/5652824 to your computer and use it in GitHub Desktop.
Save mdornseif/5652824 to your computer and use it in GitHub Desktop.
Implementation of OpenStreetmap Shortlinks in Python
@andreynovikov
Copy link

Why 56 here? I all other sources there is 58.

@johnmcd88
Copy link

johnmcd88 commented Mar 22, 2024

If anyone's interested, thanks to the folks at the Python forum I now have a functioning shortlink decode routine in Python:

`def decode(sc):
index_of = {x: y for y, x in enumerate("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
~")}
x = y = 0
z = -8
i = 0
for ch in sc:
if (digit := index_of.get(ch)) is None:
break

    # distribute 6 bits into x and y
    x <<= 3
    y <<= 3
    for j in range(2, -1, -1):
        if digit & 1 << (2 * j + 1):
            x |= 1 << j
        if digit & 1 << (2 * j):
            y |= 1 << j
    z += 3
    i += 1

x = x * 2**(2 - 3 * i) * 90 - 180
y = y * 2**(2 - 3 * i) * 45 - 90

if i < len(sc) and sc[i] == "-":
    z -= 2
    if i + 1 < len(sc) and sc[i + 1] == "-":
        z += 1

return z, y, x

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment