Search code examples
ruby-on-railsrubyruby-on-rails-3google-mapsgmaps4rails

Google Maps, Ruby on Rails, Zoom level with one marker


I am adding google maps support with apneadiving / Google-Maps-for-Rails (thanks awesome gem)

I am finding one slight glitch, however, which very likely is my fault.

auto_zoom works great when there are multiple markers. However, when there is only one marker it is zoomed in to the max level which is not pretty.

"zoom" will only work when auto_zoom is false, so that's not what I want.

So therefore you could use "maxZoom" but now users cannot zoom in manually beyond that point which is not what I want.

Is there a way around this? Is my explanation making sense? Is this a limitation of Google Maps API?

Thanks...


Solution

  • This behavior is due to the auto_zoom built-in function in the google maps api.

    One work around to this is to set it to false in the gmaps method:

    <%= gmaps({
           "map_options" => { "auto_zoom" => false},
           "markers"     => { "data" => @json }
          })
    %>
    

    And then use the gmaps4rails_callback to fit your needs (be sure to have at least version 0.7.9)

    <script type="text/javascript" charset="utf-8">
      function gmaps4rails_callback() {
        if (Gmaps4Rails.markers.length == 1) {
         //only one marker, choose the zoom level you expect
         Gmaps4Rails.map.setZoom(2);
        }
        else{
         //more than one marker, let's auto_zoom
         Gmaps4Rails.map_options.auto_zoom = true;
         Gmaps4Rails.adjust_map_to_bounds();
        }
      }
    </script>