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

后端 未结 3 1408
青春惊慌失措
青春惊慌失措 2020-12-06 12:02

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.

相关标签:
3条回答
  • 2020-12-06 12:56

    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>
    
    0 讨论(0)
  • 2020-12-06 13:06

    I achieved this in a slightly different way as I know that I'll only ever have one marker on my map. I'm relatively new to rails, but this method feels a bit "cleaner" than using JS in your view.

    I've got lat and lng stored in my model (encoded by geokit at time of creation), so did the following in my view:

    <%= gmaps({
           "map_options" => {"auto_zoom" => false, "zoom" => 15, "center_latitude" => @listing.lat, "center_longitude" => @listing.lng },
           "markers"     => {"data" => @markers }
          })
    %>
    

    @markers is my JSON created by blah.to_gmaps4rails, and "listing" is my model.

    0 讨论(0)
  • 2020-12-06 13:07

    thanks this helped me...

    {"auto_zoom" => false, "zoom" => 15, "center_latitude" => @listing.lat, "center_longitude" => @listing.lng }, "markers" => {"data" => @markers } }) %>
    0 讨论(0)
提交回复
热议问题