Rendering a Gmap through an AJAX call with Gmaps4rails

北慕城南 提交于 2019-12-20 03:19:09

问题


There are topics that try to cover this here: Gmaps4rails : map not showing when loaded dynamically and especially here: Rendering google map using gmaps4rails through Ajax, also watched the screencast in which a gmap is dynamically updated but I still don't seem to get it work.

I am trying to load the map in a drop-down tab only if a button is clicked displaying the direction between a user and an offer. In my _location.html.erb partial I have:

<%= gmaps({ "direction" => { "data" => { "from" => current_user.location, "to" => @offer.location } } })%>

(the locations are addresses)

Now this works nicely when the partial is rendered immediately. If I however try to render the partial over an AJAX call later after the whole page has already loaded initially, the gmap is not displayed. Is it possible to initialize and render the gmap through an AJAX call and display directions then?


回答1:


The reason is quite simple: the partial contains much javascript you can't load and execute this way.

So you can't use RJS there.

The proper way to do is UJS: get data with an AJAX call and render the result. In the following code, I use jQuery.

In your view add:

//include google script
<script type="text/javascript" src='http://maps.google.com/maps/api/js?sensor=false&libraries=geometry'></script>
//include gmaps4rails javascript
<%=javascript_include_tag 'gmaps4rails' %>

<script type="text/javascript" charset="utf-8">
//load map when button click (replace with what you want)
$('#ajax_map').click(function(){
  //you have to set a size to the div otherwise the map won't display, that's the purpose of these css classes
  $('#map_container').addClass('map_container');
  $('#gmaps4rails_map').addClass('gmaps4rails_map');
  //create the map object
  Gmaps4Rails.initialize();
  //of course, replace these two with your dynamic data, you'd have to use some $.ajax jQuery method.
  Gmaps4Rails.direction_conf.origin = 'toulon, france';
  Gmaps4Rails.direction_conf.destination = 'paris, france';
  //read the js file, you can customize much more: https://github.com/apneadiving/Google-Maps-for-Rails/blob/master/public/javascripts/gmaps4rails.js
  Gmaps4Rails.create_direction();
});
</script>

<div id="map_container"> 
  <div id="gmaps4rails_map"></div>
</div>

<button type="button" id="ajax_map">Ajax Map</button>

Add the following class in your CSS:

#map-container {
  width: 800px;
}

#gmaps4rails_map {
  width: 800px;
  height: 400px;
}


来源:https://stackoverflow.com/questions/6383129/rendering-a-gmap-through-an-ajax-call-with-gmaps4rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!