使用gmaps4rails动态加载Google Maps Markers
如何仅使用gmaps4rails加载地图边界内的标记? 当然,在平移和/或缩放后加载新的。
与此直接相关,我如何获得地图的当前边界和缩放级别?
我是这样做的,我只在用户完成平移或缩放后替换标记,如果你需要不同的行为,那么使用不同的事件监听器:
在您的视图中(index.html.erb):
<%= gmaps({ "map_options" => { "zoom" => 15, "auto_adjust" => false, "detect_location" => true, "center_on_user" => true }}, false, true) %>
在视图的底部添加:
在application.js中(使用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#指数:
def index # Only pull venues within the visible bounds of the 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 do |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模型(使用mongodb和mongoid):
def self.within_bounds(bounds) self.where(:location.within => {"$box" => bounds }) end
哇,你真的为gem提供了很多反馈:)
这是我如何使用它:
-
要加载有用的标记,我使用geokit-rails3和以下范围过滤它们:
Location.in_bounds([@south_west_point, @north_east_point], :origin => @somewhere)
-
当缩放或跨度时,我只依赖于固定过程的聚类
-
配置,地图中心和原始缩放,请参见此处
-
你应该自己编写获取当前边界的方法,考虑拉动:)