I wrote this translation of the PolylineEncoder.js by Mark McClure because I needed a way to create encoded polylines for Google maps. When I first started my project - http://nomadexplorers.com.

I tried using an existing ruby translation of PolylineEncoder.js. It was giving me some errors when I tried using it and it only took an array of coordinates. For my needs I needed the class to accept an array of objects. This seems a bit more elegant to me. Also, in the notes that where provided in the class comments, it appeared to have a bug that would incorrectly encode the second point. So instead of trying to debug and rewrite their code, I just decided to do my own implementation.

This is an exact line for line port of the javascript version by Mark McClure that uses the Douglas-Peucker algorithm. You would use it the same way as the javascript version. Below is an example on how you might use it in your own ruby app. To use it with rails just put it inside your lib directory.

# A simple point class example:
# You will probably want to use something different
# Remember dp_encode accepts an array of objects

class Point
attr_accessor :lat, :lng
def initialize(lat, lng)
@lat, @lng = lat, lng
end
end

points = Array.new
points << Point.new(36.97005, -93.29783)
points << Point.new(36.97005, -93.29410000000001)
points << Point.new(36.96998, -93.28758)

# Actual usage of the Polyline Encoder
polyline_encoder = PolylineEncoder.new
polyline_encoder.dp_encode(points)

polyline_encoder.encoded_points
polyline_encoder.encoded_levels

I am also working on the decoder so you can easily decode an encoded polyline. Check back soon I am almost done. If you would like to use the Ruby class in your own projects, feel free to do so.

Download - polyline_encoder.rb.