Using Google Maps API (v3) with Rails (5.2)

Paulo Belo
9 min readSep 22, 2018

Step-by-Step Tutorial

In this tutorial we’ll talk about how to use Google Maps API with Rails. We’ll see some examples of using Static API and Javascript API, how to place a marker and how to update the marker position when we change a form input value. And finally how to update the input value by dragging the marker. All of this without using any gems.

Level: beginner

Pre requisites: basic knowledge of Rails and Javascript

Setup Rails

Please confirm that you have rails >= 5.2 installed (so you can use Rails Credentials)

rails -v

Now let’s create a rails App:

rails new gmaps-rails-example
cd gmaps-rails-example

Let’s continue by creating a basic CRUD App, scaffolding ´Place´:

rails g scaffold Place name:string latitude:decimal longitude:decimal --javascript-engine=js

We have created a Model that holds basic information (name and location) about places, with these fields and types:

  • name: string
  • latitude: decimal
  • longitude: decimal

and the correspondent controller, views, routes and assets.

Coffescript is a great language and much more elegant then javascript, but I find easier to work with javascript because we can find more examples and snippets in the internet. In this case, all of Google Maps API Documentation code examples are in Javascript. So we use the parameter --javascript-engine to tell rails to use Javascript in scaffold.

and now let’s create the database:

rails db:migrate

and populate with some data. Edit db/seeds.rb file and add:

Place.create!([
{ "name": "Buckingham Palace", "latitude": "51.501564","longitude": "-0.141944"},
{ "name": "Westminster Abbey", "latitude": "51.499581", "longitude": "-0.127309"},
{ "name": "Big Ben", "latitude": "51.500792", "longitude": "-0.124613"}
])

now run:

rails db:seed

--

--

Paulo Belo

Developer. Freelancer. Looking for the right words, mainly in ruby and dart.