以下のページを参考に作らせていただきました。感謝。
https://www.codeproject.com/Tips/312248/Google-Maps-Direction-API-V3-Polyline-Decoder
ビット演算とか全然やったことなかったので、勉強になりました。
def decode_polyline(enc: str):
"""
Parameters
----------
enc : str
encoded string of polyline, which can be aquired via Google Maps API.
Returns
-------
result : list
each element in `result` contains pair of latitude and longitude.
"""
if enc == None or enc == '':
return [[0, 0]]
result = []
polyline_chars = list(enc.encode())
current_latitude = 0
current_longitude = 0
try:
index = 0
while index < len(polyline_chars):
# calculate next latitude
total = 0
shifter = 0
while True:
next5bits = int(polyline_chars[index]) - 63
index += 1
total |= (next5bits & 31) << shifter
shifter += 5
if not(next5bits >= 32 and index < len(polyline_chars)):
break
if (index >= len(polyline_chars)):
break
if((total & 1) == 1):
current_latitude += ~(total >> 1)
else:
current_latitude += (total >> 1)
# calculate next longitude
total = 0
shifter = 0
while True:
next5bits = int(polyline_chars[index]) - 63
index += 1
total |= (next5bits & 31) << shifter
shifter += 5
if not(next5bits >= 32 and index < len(polyline_chars)):
break
if (index >= len(polyline_chars) and next >= 32):
break
if((total & 1) == 1):
current_longitude += ~(total >> 1)
else:
current_longitude += (total >> 1)
# add to return value
pair = [current_latitude / 100000, current_longitude / 100000]
result.append(pair)
except:
pass
return result