Created
February 21, 2019 17:14
-
-
Save jeremycochoy/5e2c0363cf462e8cd00eeb4c6a3e28c4 to your computer and use it in GitHub Desktop.
Encode polyline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def encode(points, precision = 1e5) | |
result = "" | |
last_lat = last_lng = last_timestamp = 0 | |
# Convert each point (lat, lng, ts) to a string | |
points.each do |point| | |
# Convert to integer | |
lat = (point[0] * precision).round | |
lng = (point[1] * precision).round | |
timestamp = point[2] | |
# Compute the difference with the previous point | |
diff_lat = lat - last_lat | |
diff_lng = lng - last_lng | |
diff_timestamp = timestamp - last_timestamp | |
# See fast-polyline github repository for encode_number | |
chunks_lat = encode_number(diff_lat) | |
chunks_lng = encode_number(diff_lng) | |
chunks_ts = encode_number(diff_timestamp) | |
# Glue the strings together | |
result << chunks_lat << chunks_lng << chunks_ts | |
# Save the current point for computing the differences later | |
last_lat = lat | |
last_lng = lng | |
last_timestamp = timestamp | |
end | |
# The encoded string: | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment