Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is how I did it, I only replace the markers after the user finishes panning or zooming, if you require different behavior then use a different event listener:</p> <p>In your view (index.html.erb):</p> <pre><code>&lt;%= gmaps({ "map_options" =&gt; { "zoom" =&gt; 15, "auto_adjust" =&gt; false, "detect_location" =&gt; true, "center_on_user" =&gt; true }}, false, true) %&gt; </code></pre> <p>At the bottom of your view add:</p> <pre><code>&lt;script type="text/javascript" charset="utf-8"&gt; function gmaps4rails_callback() { google.maps.event.addListener(Gmaps4Rails.map, 'idle', function () { var bounds = Gmaps4Rails.map.getBounds(); drawItems(bounds); }); } &lt;/script&gt; </code></pre> <p>In application.js (using jQuery):</p> <pre><code>function drawItems(theBounds) { var url = '/venues.json/?sw_y=' + theBounds.getSouthWest().lng() + '&amp;sw_x=' + theBounds.getSouthWest().lat() + '&amp;ne_y=' + theBounds.getNorthEast().lng() + '&amp;ne_x=' + theBounds.getNorthEast().lat(); $.get(url, function(newItemData) { Gmaps4Rails.replace_markers(newItemData); }); } </code></pre> <p>venues_controller#index: </p> <pre><code>def index # Only pull venues within the visible bounds of the map if (params[:sw_y] &amp;&amp; params[:sw_x] &amp;&amp; params[:ne_y] &amp;&amp; params[:ne_x]) bounds = [ [params[:sw_x].to_f, params[:sw_y].to_f], [params[:ne_x].to_f, params[:ne_y].to_f] ] @venues_within_bounds = Venue.within_bounds(bounds) else @venues_within_bounds = Venue.all end respond_to do |format| format.html # index.html.erb format.json { @data = @venues_within_bounds.collect {|v| { :longitude =&gt; v.longitude, :latitude =&gt; v.latitude, :picture =&gt; v.marker_picture, :title =&gt; v.marker_title } render :json =&gt; @data } end end </code></pre> <p>Venue.rb model (using mongodb and mongoid):</p> <pre><code>def self.within_bounds(bounds) self.where(:location.within =&gt; {"$box" =&gt; bounds }) end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload