Skip to content

Instantly share code, notes, and snippets.

@ethanal
Created October 3, 2014 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ethanal/4f92ce7ea87d06c19073 to your computer and use it in GitHub Desktop.
Save ethanal/4f92ce7ea87d06c19073 to your computer and use it in GitHub Desktop.
Encode Polyline for Google Static Maps API
def invert(b):
return "".join(str(int(not int(c))) for c in b)
def encode_float(f):
b = bin(abs(int(round(f * 1e5))))[2:]
b = ("0" * (32 - len(b))) + b
if f < 0:
b = invert(b)
b = bin(int(b, 2) + 1)[2:]
b = b[1:] + "0"
if f < 0:
b = invert(b)
if len(b) % 5 != 0:
b = "0" * (5 - (len(b) % 5)) + b
chunks = [b[5 * s:5 * (s + 1)] for s in range(len(b) // 5)]
while len(chunks) > 1 and chunks[0] == "00000":
chunks.pop(0)
chunks = chunks[::-1]
chunks = [int(c, 2) | (0x20 * (i != len(chunks) - 1)) for i, c in enumerate(chunks)]
return "".join(chr(c + 63) for c in chunks)
def encode_polyline(points):
for i in reversed(range(len(points) - 1)):
points[i + 1][0] -= points[i][0]
points[i + 1][1] -= points[i][1]
return "".join(encode_float(lo) + encode_float(la) for lo, la in points)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment