Google Maps has a well-documented API for customising maps with your own imagery and content. For a side project built with Ruby on Rails, I wanted to allow users to freehand highlight routes on a map and save them for future viewing and modifying. The best way seemed to be to use complex polylines and save the lines as an overlay paired with the map window information. Here is a straightforward way of doing it cleanly within the Rails framework.
The premise of the project is allowing people (whether Post employees, menu/flyer distributors, etc.) doing door-to-door distribution to track where they’ve distributed, or to plot out where they need to distribute, on a Google map. While the project is currently live, it is still in progress and being tested, so I won’t share the link at this time.
As pictured above, to draw on the map, users tap a starting point, which will be joined to any consecutive point they tap with a straight yellow line. To end a path, users tap twice, and then they can begin new paths as they like.
Setting up the view templates
html.erb templates. First, I created a new partial template called
_googlemap.html.erb within my views folder under the relevant model. For now, the template contains a single line:
My model saves both the routing/map information, as well as some additional fields. All the routes information will be stored in a hidden
routes field. Next, in the
_form.html.erb template for my model, I rendered the partial template where I wanted the map to appear.
<!-- The generated form field for my model field called routes; hidden --> <div class="form-group hidden-field" id="distribution-routes"> <%= f.label :routes %> <%= f.text_field :routes %> </div> <div id="editing-field" class="hidden-field"><%= @editing %></div> <div id="latitude-field" class="hidden-field"><%= @latitude %></div> <div id="longitude-field" class="hidden-field"><%= @longitude %></div> <%= render :partial => "map" %>
Using css, I hide the
Drawing and viewing routes as overlays
The Google Maps API for complex polylines has good documentation with sample code to get you started. I registered my app, got a unique API key, then took their sample code as the base. Here is my code, with commentary.
Saving routes as JSON as a Rails model field
In the script above, all the routes are parsed and saved in JSON format. Rather than convert the JSON to a String in the controller before saving the models, I made the
routes field in my schema of type JSON.
create_table "distributions", force: :cascade do |t| t.jsonb "routes"
A few features I am currently working on are:
- sorting distributions based on map routes
- merging overlays from multiple maps and saving
- multiple highlighting colours
- opening the map in a whole new window for easier navigation (on mobile or tablet, scrolling and zooming can be tricky because the map is embedded in the page)
If I’ve missed something or parts are not clear, please let me know and I’ll do my best to clarify!