Using Google Maps along with pagination in Rails

193 views Asked by At

I have a view on which I'm trying to display a paginated list of objects as well as a Google Map displaying those objects. I have a 'Trip' view which displays 'Points' belonging to that trip. Each point has a lat/lng. The page initially loads correctly, but when I move to different pages I start getting errors like:

"You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

message: "not a LatLng or LatLngLiteral: in property lat: not a number"
name: "InvalidValueError"

In my Gemfile:

gem 'gmaps4rails',    '2.1.2'
gem 'underscore-rails'
gem 'gmaps'

In app/assets/javascripts/application.js:

//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require underscore
//= require gmaps/google
//= require_tree .

My controller:

  def show
    @trip = Trip.find(params[:id])
    @trip_points = @trip.trip_points

    @markers = Gmaps4rails.build_markers(@trip_points) do |pt, marker|
      next if pt.lat.nil? || pt.lon.nil?
      marker.lat pt.lat
      marker.lng pt.lon
    end
    @markers.reject! { |m| m.empty? }
    @trip_points = @trip_points.paginate(page: params[:page])
  end

I want to display all points on the map, while paginating the view of the points.

My view:

<script src="//maps.google.com/maps/api/js?key=MYAPIKEY" type="text/javascript"></script>
<script src="//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js"></script>

<div class="row">
  <aside class="col-md-6">
    <%= will_paginate @trip_points %>
    <ul class="trip_points">
      <% if @trip.trip_points.any? %>
        <%= render @trip_points %>
      <% else %>
        <%= render 'trip_points/add_point', last: true, index: 0 %>
      <% end %>
    </ul>
    <%= will_paginate @trip_points %>

  </aside>
  <div class="col-md-6">
    <div id="map" style='width: 100%; height: 800px; margin-top: 2em;'></div>
  </div>
</div>

<script type="text/javascript">
  handler = Gmaps.build('Google');
  handler.buildMap({ provider: {},
                     internal: {id: 'map'}},
                     function(){
    markers = handler.addMarkers( <%= raw @markers.to_json %> );
    handler.bounds.extendWith(markers);
  });
</script>

I have a partial _trip_point_.html.erb

As far as I can tell, I'm only including the Google Maps API once on my page. Should the .js go somewhere else in the application?

1

There are 1 answers

0
Greg Merritt On

To fix this I moved the first two <script> tags from the view into the <head> section of views/layouts/application.html.erb