LoginSignup
0
0

More than 3 years have passed since last update.

Google Maps APIのPolyLineをデコードする関数(Python3)

Last updated at Posted at 2020-04-24

以下のページを参考に作らせていただきました。感謝。
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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0