Skip to content

Instantly share code, notes, and snippets.

@harryworld
Created October 28, 2014 07:00
Show Gist options
  • Save harryworld/1f46688f3689a58dd8ac to your computer and use it in GitHub Desktop.
Save harryworld/1f46688f3689a58dd8ac to your computer and use it in GitHub Desktop.
Add Google Map in Rails

Google Map for Rails

Gmaps4rails is developed to simply create a Google Map with overlays (markers, infowindows…).

Requirements

  1. Create an empty repository in GitHub, named googlemaps, select the READM, license, and rails .gitignroe file
  2. Clone the repository to local workspace folder
  3. cd googlemaps
  4. rails _4.1.6_ new . -BGT
  5. git add -A
  6. git commit -m "Initial Commit."
  7. git push

Steps

  1. Gemfile
# Show Google Maps in rails application
gem 'gmaps4rails'

# Geocoding solution in rails application
gem 'geocoder'

# Frontend JavaScript library used by Google Map Utilities
gem 'underscore-rails'

Run bundle install in Terminal

  1. JavaScript Dependencies

You'll need to import Google Map JS API, and the Google Map utlities for this to work Insert the following code into application.html.erb, at the bottom just before the end of body

  <%= javascript_include_tag '//maps.google.com/maps/api/js?v=3.13&amp;sensor=false&amp;libraries=geometry' %>
  <%= javascript_include_tag '//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js' %>

  1. Scaffold the Place resource
rails generate scaffold Place name:string address:string lat:float lng:float

The generated resources would include:

  • Routes
  • Controller
  • Views
  • Model
  • CoffeeScript
  • jBuilder
  1. Prepare the Database structure
rake db:migrate
  1. Setup the routes

In routes.rb, make sure you have the following two lines uncommented.

  resources :places

  root 'places#index'

Now, you are able to visit the site by http://localhost:3000/, and view the site.

  1. Geocoding the latitude/longitude

When we create the new venue, we don't know the latitude and longitude. Thus, we want to provide the address, and use some 3rd party service to convert it to lat/lng

We installed the corresponding gem geocoder already, we need to put some additional code to the model Place.

  reverse_geocoded_by :lat, :lng
  after_validation :reverse_geocode  # auto-fetch address
  geocoded_by :address, :latitude  => :lat, :longitude => :lng   # can also be an IP address
  after_validation :geocode          # auto-fetch coordinates

Now, create your first location, with only the name and address, the latitude and longitude will be filled in automatically.

  1. Test the API

Rails scaffold builds the JSON API for us as well, using jBuilder, we can test out by visiting the following in the browser. The APIs are RESTful, and in JSON format.

http://localhost:3000/places.json
http://localhost:3000/places/1.json
  1. Create new route, and controller action to show the map

We are going to create a new route map in the routes.rb, so that it looks like this:

  resources :places

  root 'places#index'

  get 'map' => 'places#map'

Then we are adding the map method in places_controller.rb, it looks like this:

  # GET /map
  def map
  end

Create an empty html file under app/views/places folder, named map.html.erb, then put the following in the file.

<div id="map"></div>

Lastly, in the application.css, put the following to create an area for the map.

#map {
  width: 800px;
  height: 400px;
}
  1. Import

Open the file places.js.coffee, this file will be loaded in all places views. We are going to add some codes here.

Import the underscore and gmaps javascript source code to this by adding the following at the top.

#= require underscore
#= require gmaps/google
  1. Start working on jQuery part by adding Google Map function, using CoffeeScript
@googleMap = (content) ->
  handler = Gmaps.build("Google")
  handler.buildMap
    provider: {}
    internal:
      id: "map"
  , ->
    markers = handler.addMarkers(content)
    handler.bounds.extendWith markers
    handler.fitMapToBounds()

See the references from http://apneadiving.github.io/

  1. Create the jQuery function

Add the following code to the bottom of same CoffeeScript file, with some hardcoded data.

content = [
  {lat: 0, lng: 0,infowindow: "hello!", link: 'a'},
  {lat: 20, lng: 120,infowindow: "hello!", link: 'b'}
]

$ ->
  $.ajax
    url: '/places.json'
  .done (data) ->
    googleMap content

Visit the page http://localhost:3000/map, a map will be shown, with two pins.

  1. Convert our JSON data into compatible array
@convert = (objects) ->
  array = []

  for x in objects
    y =
      lat: x.lat
      lng: x.lng
      infowindow: x.name
    array.push y

  googleMap array
  1. Final CoffeeScript file would look like this
#= require underscore
#= require gmaps/google


@convert = (objects) ->
  array = []

  for x in objects
    y =
      lat: x.lat
      lng: x.lng
      infowindow: x.name
    array.push y

  googleMap array

@googleMap = (content) ->
  handler = Gmaps.build("Google")
  handler.buildMap
    provider: {}
    internal:
      id: "map"
  , ->
    markers = handler.addMarkers(content)
    handler.bounds.extendWith markers
    handler.fitMapToBounds()

$ ->
  $.ajax
    url: '/places.json'
  .done (data) ->
    convert data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment