Monthly Archives: June 2013

Drawing Polylines with Rails and Google Maps

Chances are, you have dabbled into adding push pins onto a google map. It’s a pretty easy process, involving a latitude and longitude, which can then be turned into a pin using the google.maps.Marker() function. However, you may not have played with drawing a route with google maps. It turns out, that if you have a series of latitude and longitude points in a database, it is pretty simple to draw them onto a google map.

Rails to the rescue

For our example, we would like to retrieve some lat/lon coordinates from the database and “encode” them in the polyline format. Polyline Reference Once we have the points in the polyline format, we should be able to draw them on a google map. For simplicity, we will use rails on the server to query and transform these points.

Lat Lon
44.928729 -93.167033
44.928729 -93.167033

Assuming that we have data a “shapes” table like above, we should be able to easily query this out with active record and map it to an array of lat/lon points.

Now that the data is in a usable format we need to encode it to the polyline format. To do this we can use a gem called polylines. Just add the following to your gemfile.

At this point polylines should be available to use. It should be as simple as encoding the points.

If successful, you should get some encoded output like below. If so, congratulations you can move on the the final step!

Map it like it’s hot

Now that we have everything worked out on the server, we just need to draw it on the map. First, we are going to need to setup a map object.

Next, we need to setup a polyline object. We can adjust the stroke color, opacity and weight via configuration options. Once the poly object is created, the last thing we need to do is associate it with the map object. The setMap() function will create this association.

At this point, everything should be setup to draw on the map. All we need to do is take our encoded result from the server and set the path on our polyline object.

In the example above, the path variable is referring to the encoded server result. We use the decodePath function to decode our result, and then pass that value into the setPath() function on our polyline object. If all goes according to plan, we should get a blue line like so…

buses-path