I am working with the polyline of google, I would like to give a set of coordinates and generate the correct polyline and viceversa. In particular in the end i would like to url encode the result (the polyline). When I insert a polyline like:
code = '((akntGkozv@kcCka@us@y{DfvAm{BnuCj_Aus@fzG))'
I use the polyline
package: https://pypi.org/project/polyline/, and first I decode the polyline in order to see the coordinates:
coordinates = polyline.decode(code)
print(coordinates)
>> [(3e-05, -0.0001), (-0.0001, -7e-05), (-0.0002, -0.0002), (45.46221, 35.36626), (45.4621, 35.36617), (45.48328, 35.39727), (45.48317, 35.39718), (45.5172, 35.39707), (45.51711, 35.39816), (45.51723, 35.39814), (45.5172, 35.38418), (45.51823, 35.3843), (45.51821, 35.38428), (45.49413, 35.37398), (45.52816, 35.37387), (45.52807, 35.32855), (45.5281, 35.32845), (45.52823, 35.32848), (45.52813, 35.32861)]
and everything here is fine, the problems comes when I try to encode the coordinates back to the polyline (which is my ultimate goal since in the end i would like to give some coordinates and obtain the corresponding polyline)
new_code = polyline.encode(coordinates)
print(new_code)
>> ERXERXakntGkozvETPkcCkaETPusETPyEWBDfvAmEWBBnuCj_AusETPfzGERYERY
Which is slightly different from the original and if put back in the url it doesnt work!
So my question here are:
what kind of encoding is
new_code
? I have tried to encode it in percentage url usingurllib.parse.quote(new_code)
but the result is exactly the same, maybe I neeed to specify some particular encoding style but i didnt found anything.The polyline that I used is a square inside the city of Milan (so only 4 points, maximum 5, are required to identify this area), but the coordinates results from the
polyline.decode
gives me back a list with 19 points with coordinates that are not even close to the city of Milan. Why?
CodePudding user response:
Ok so basically all of my problems came from the fact that the string i was considering: ((akntGkozv@kcCka@us@y{DfvAm{BnuCj_Aus@fzG))
contains ((
and ))
which are not part of the polyline but are simply two ((
and ))
inserted by the particular url of the site I was using. A simple replace and an encode return the correct polyline:
code = '((akntGkozv@kcCka@us@y{DfvAm{BnuCj_Aus@fzG))'
code = code.replace('(', '').replace(')', '')
code = urllib.parse.unquote(code)
print(code)
>> irotG_hzv@woBmE}i@yjE`oBwkDf|ChRhMzeG}~BxcB
Which infact, if put inside the polyline.decode
returns exactly the coordinates that I have used:
coordinates = polyline.decode(code)
print(coordinates)
>> [(45.46869, 9.15088), (45.48673, 9.15191), (45.4936, 9.18452), (45.47567, 9.21216), (45.45051, 9.20907), (45.44822, 9.16701), (45.46869, 9.15088)]
Which are exactly 7 (now i have changed the shape so a sixtagon instead of a square) and points exactly in the city of Milan