Plotting coordinates: a simple gon gem tutorial
This tutorial will walk a rails beginner through the process of how to plot coordinates on a google map. This method is quick and easy, and will be relatively pain free.
First, add the gem gon to your gemfile:
What does gon do for you?
It allows you to write data in your controller (or presenter or model) to a variable
(You'll see that I have included the awesome gem geocoder. I used this gem to retrieve the coordinates of a visitor to my app via their IP addesss.)
Then be sure to bundle install after adding the gems to your gemfile.
Using gon is the simplest thing in the world. You merely assign some data to a variable with "gon."" as a prefix in your controller.
As you can see, I used the same format as I did for the instance variables I will use in my view, only replacing the '@' with 'gon'.
In the Visitors model, I use the geocoder gem to assign latitude and longitude values to the object before saving to the database.
The geocoder documentation explains this well, but in order to plot these two separate values as one marker, we are going to want to have them as an array of arrays for each entry, like this: [[lat, long], [lat, long], [lat, long]...].
As you can see, I am plucking out the latitude and longitude values of all Visitors and assigning those resulting arrays to varibles. Then I use the zip method to turn it into the array of arrays I need. Before returning the variable, be sure to delete any of the arrays if they include nil or a coordinate of "0.0".
This is sort of a long method; if I were to refactor it, I would probably start by moving the delete_ifs out to a separate method since their concerns are different from the previous lines that query the database.
Here's what it looks like on the page:
You can see this in action, along with my first attempts to use the canvas element over at liz-newsletter.herokuapp.com, my Ada winter break project.