#86 Plotting Points on a Map from Scratch


Using the Google Maps Javascript API, learn how to plot markers onto a map. Load markers and info windows through AJAX calls to your Rails JSON API.
rails javascript api maps view ajax 8:33


routes.rbresources :stores do
  resources :operation_hours
  collection do 
    get :map
<div id='map'></div>
layouts/application.html.erb<%= tag :meta, name: 'google_maps', content: 'YOUR_API_KEY' %>
application.js$(document).on('turbolinks:load', function(){
  if ($('#map').length > 0){
    var google_map = $('meta[name=google_maps]').attr("content");
stores.coffee@initMap = ->
  center = 
    lat: 0
    lng: 0

  map = new (google.maps.Map) $('#map')[0],
    zoom: 2
    center: center

  infowindow = new (google.maps.InfoWindow)

  $.getJSON '/stores.json', (jsonData) ->
    $.each jsonData, (key, data) ->
      latLng = new (google.maps.LatLng)(data.lat, data.lng)
      marker = new (google.maps.Marker)
        position: latLng
        map: map
        title: data.title
      google.maps.event.addListener marker, 'click', ->
          content: data.content
          maxWidth: 300
        infowindow.open map, marker
stores/index.json.jbuilderjson.array! @stores do |store|
  json.lat store.latitude
  json.lng store.longitude
  json.title store.name
  json.content StoresController.render(partial: 'stores/store', locals: { store: store }, format: :html).squish
stores/_store.html.erb<h1><%= store.name %></h1>
<h2>Hours of Operation</h2>
  <% store.operation_hours.each do |operation_hour| %>
    <li><strong><%= operation_hour.day.titleize %></strong> - <%= operation_hour.hours %></li>
  <% end %>
stores_controller.rbclass StoresController < ApplicationController
  def index
    @stores = Store.includes(:operation_hours).all
Nickiam said over 1 year ago:

Thanks, Dave!

Really enjoying the maps episodes!

dancinglightning said over 1 year ago:

Yes, thanks for that.

Did you see a way of getting from actual addresses to those coordinates that you used ?

kobaltz PRO said over 1 year ago:

Check out episode 84 where the geocoding from street address to coordinates is done via the geocoder gem.

Silviu Salajan said over 1 year ago:

It works on local environment but in production mode (heroku) don't.

Thank you for this tutorials!

Silviu Salajan said over 1 year ago:

I put this <script src="https://maps.googleapis.com/maps/api/js?key=$API_KEY&callback=initMap" async> </script> on recipes/map.html.erb and i removed all application.js code and meta tag with api key from layouts/application.html.erb because it dosen't work in production. Thanks!

kobaltz PRO said over 1 year ago:

Any JS errors?

Silviu Salajan said over 1 year ago:

Yes because of `` used on  $.getScript(`https://maps.googleapis.com/maps/api/js?key=${google_map}&callback=initMap`); :D

Login to Comment