ruby on rails - Dynamically load Google Maps Markers with gmaps4rails -
how load markers inside map bounds gmaps4rails? , of course load new ones after pan and/or zoom.
directly related that, how can current boundaries , zoomlevel of map?
here how did it, replace markers after user finishes panning or zooming, if require different behavior use different event listener:
in view (index.html.erb):
<%= gmaps({ "map_options" => { "zoom" => 15, "auto_adjust" => false, "detect_location" => true, "center_on_user" => true }}, false, true) %>
at bottom of view add:
<script type="text/javascript" charset="utf-8"> function gmaps4rails_callback() { google.maps.event.addlistener(gmaps4rails.map, 'idle', function () { var bounds = gmaps4rails.map.getbounds(); drawitems(bounds); }); } </script>
in application.js (using jquery):
function drawitems(thebounds) { var url = '/venues.json/?sw_y=' + thebounds.getsouthwest().lng() + '&sw_x=' + thebounds.getsouthwest().lat() + '&ne_y=' + thebounds.getnortheast().lng() + '&ne_x=' + thebounds.getnortheast().lat(); $.get(url, function(newitemdata) { gmaps4rails.replace_markers(newitemdata); }); }
venues_controller#index:
def index # pull venues within visible bounds of map if (params[:sw_y] && params[:sw_x] && params[:ne_y] && 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 |format| format.html # index.html.erb format.json { @data = @venues_within_bounds.collect {|v| { :longitude => v.longitude, :latitude => v.latitude, :picture => v.marker_picture, :title => v.marker_title } render :json => @data } end end
venue.rb model (using mongodb , mongoid):
def self.within_bounds(bounds) self.where(:location.within => {"$box" => bounds }) end
Comments
Post a Comment