Gmaps4rails показывает карту только в том случае, если в проводнике есть действие рендеринга (консоль, изменение размера)

Я пытаюсь использовать gmaps4rails, я следовал руководству из репозитория github, но карта не отображается, если я не активирую консоль или не изменяю размер окон. Я добавил событие щелчка, чтобы добавить метку, и метка появляется, но карта не отображается. Я показываю карту во всплывающем окне

Любая идея? любая помощь будет признательна

Это мой гемфайл

gem "rails", "4.1.1"
gem "mongoid", github: "mongoid/mongoid"
gem "sass-rails", ">= 3.2"
gem "uglifier", ">= 1.3.0"
gem "coffee-rails", "~> 4.0.1"
gem "therubyracer", platforms: :ruby
gem "jquery-rails"
gem "jquery-ui-rails"
gem "jquery-turbolinks"
gem "turbolinks"
gem "jbuilder", "~> 1.2"
group :development do
  gem "guard-rspec"
  gem "pry"
  gem "quiet_assets"
  gem "thin"
end

group :development, :test do
  gem "zeus"
  gem "rspec-rails"
  gem "factory_girl_rails"
end

group :test do
  gem "mongoid-rspec"
  gem "ffaker"
  gem "simplecov", require: false
  gem "database_cleaner"
  gem "rb-inotify", "~> 0.9"
end

gem "bootstrap-sass", "~> 3.3.6"
gem "font-awesome-sass-rails"
gem "simple_form", github: "plataformatec/simple_form"
gem "devise", "~> 3.0.0"
gem "cancan"
gem "omniauth"
gem "omniauth-facebook"
gem "omniauth-twitter"
gem "hashugar", github: "alex-klepa/hashugar"
gem "paperclip"
gem "mongoid-paperclip", :require => "mongoid_paperclip"
gem "country_select"
gem "city-state"
gem 'rails-jquery-autocomplete'
gem 'underscore-rails'
gem 'gmaps4rails'

это мой application.js:

//= require jquery
//= require jquery_ujs
//= require jquery.turbolinks
//= require turbolinks
//= require bootstrap
//= require jquery-ui/autocomplete
//= require autocomplete-rails
//= require underscore
//= require gmaps/google
//= require_tree .

это мой код javascript:

function initialize(){
        handler = Gmaps.build('Google',{mapTypeId: google.maps.MapTypeId.ROADMAP, zoom:8});
      handler.buildMap({ provider: {}, internal: {id: 'map' }}, function(){
      if(navigator.geolocation)
        navigator.geolocation.getCurrentPosition(displayOnMap);
      });
      handler.current_marker = null;

      function displayOnMap(position){
        handler.map.centerOn(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
        handler.fitMapToBounds();
      };  

      function placeMarker(location) {
          if(handler.current_marker === null){
            handler.current_marker = new google.maps.Marker({
                position: location, 
                map: handler.getMap(),
                draggable:true,
                "picture": {
                  "url": "http://people.mozilla.com/~faaborg/files/shiretoko/firefoxIcon/firefox-32.png",
                  "width":  32,
                  "height": 32
                }
            });
          }
          else{

            handler.current_marker.setPosition(location);

          }
          console.log(location);
      };

      google.maps.event.addListener(handler.getMap(), 'click', function(event) {
          placeMarker(event.latLng);
      });

    }

и, наконец, это мой html:

<script src="//maps.google.com/maps/api/js?v=3.18&key=AIzaSyB4enUtJizko-Wj8yZ9TylVcjRecrypOKo&sensor=false"></script> 
<script src="//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js"></script>
<!--script src='//google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.9/src/infobox_packed.js' type='text/javascript'></script--> 
<!-- only if you need custom infoboxes -->
<div id="postModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog">
  <div class="modal-content">
      <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      Add Location
      </div>
      <div class="modal-body row">
        <div class='col-md-12'>

        <%= simple_form_for @location, remote: true, format: :json do |f| %>
          <%= f.error_notification %>

          <div class="form-inputs">
            <%= f.input :name %>

            <%= f.label :point %>
            <div style='width: 98%; text-align: center;'>
              <div id="map" style='width: 100%; height: 300px;'></div>
            </div>
            <%= f.label :country %>
            <%= f.country_select("country", ["Colombia", "Argentina"], {}, {class: "form-control", id: "country"} )%>
            <%= f.select :state , options_from_collection_for_select(@states, :first, :last), {}, {class: 'form-control'}  %>
            <%= f.select :city , options_for_select(@cities.each{|a| [ a, a ] }), {}, {class: 'form-control'} %>
          </div>


        </div>


      </div>
      <div class="modal-footer">
        <div>
            <%= f.button :submit, 'Save', :class => "btn btn-primary btn-sm" %>

            <ul class="pull-left list-inline"><li><a href=""><i class="glyphicon glyphicon-upload"></i></a></li><li><a href=""><i class="glyphicon glyphicon-camera"></i></a></li><li><a href=""><i class="glyphicon glyphicon-map-marker"></i></a></li></ul>
        </div>  
      </div>
      <% end %>
      <br/>
  </div>
  </div>
</div>

person damianfabian    schedule 01.03.2016    source источник


Ответы (2)


Удалите "fade" из модального окна начальной загрузки twitter. Ниже приведен исправленный код вашего модального всплывающего окна.

<div id="postModal" class="modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog">
  <div class="modal-content">
      <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      Add Location
      </div>
      <div class="modal-body row">
        <div class='col-md-12'>

        <%= simple_form_for @location, remote: true, format: :json do |f| %>
          <%= f.error_notification %>

          <div class="form-inputs">
            <%= f.input :name %>

            <%= f.label :point %>
            <div style='width: 98%; text-align: center;'>
              <div id="map" style='width: 100%; height: 300px;'></div>
            </div>
            <%= f.label :country %>
            <%= f.country_select("country", ["Colombia", "Argentina"], {}, {class: "form-control", id: "country"} )%>
            <%= f.select :state , options_from_collection_for_select(@states, :first, :last), {}, {class: 'form-control'}  %>
            <%= f.select :city , options_for_select(@cities.each{|a| [ a, a ] }), {}, {class: 'form-control'} %>
          </div>


        </div>


      </div>
      <div class="modal-footer">
        <div>
            <%= f.button :submit, 'Save', :class => "btn btn-primary btn-sm" %>

            <ul class="pull-left list-inline"><li><a href=""><i class="glyphicon glyphicon-upload"></i></a></li><li><a href=""><i class="glyphicon glyphicon-camera"></i></a></li><li><a href=""><i class="glyphicon glyphicon-map-marker"></i></a></li></ul>
        </div>  
      </div>
      <% end %>
      <br/>
  </div>
  </div>
</div>
person chaitanya    schedule 01.03.2016
comment
Привет, спасибо за ответ, я сделал это, но не работает, поэтому я удалил все классы из всплывающего окна, и теперь я вижу карту, но похоже, что бутстрап отключил мое всплывающее окно. В любом случае, большое спасибо за подсказки ... Я мог бы потратить дни, пытаясь найти проблему. - person damianfabian; 01.03.2016
comment
У меня была такая же проблема, я только что удалил затухание, где бы я ни объявил, и всплывающее окно работает для меня, показывает ли консоль какую-либо ошибку для вас? - person chaitanya; 01.03.2016
comment
нет, я не получаю никаких ошибок. Это странно, я проверю все свои стили, чтобы понять, в чем проблема. - person damianfabian; 01.03.2016
comment
Большое вам спасибо за то, что направили меня на правильный путь. Столько времени было потрачено на решение этой проблемы. - person damianfabian; 01.03.2016
comment
Нет проблем, я был бы более счастлив, если решение сработало для вас идеально. - person chaitanya; 01.03.2016

Проблема и решение, которое объясняется в этом вопросе. В основном вам нужно добавить это событие, чтобы исправить проблему:

$("#postModal").on("shown.bs.modal", function () {
   google.maps.event.trigger(map, "resize");
}); 

где карта - это экземпляр вашей карты Google.

person damianfabian    schedule 01.03.2016