Providing Gmap via an AJAX call using Gmaps4rails

There are topics here that try to cover this: Gmaps4rails: the map does not appear during dynamic loading and especially here: Rendering a google map using gmaps4rails via Ajax also looked at the screencast in which gmap is dynamically updated, but I still don't understand how it works .

I try to load the map in the drop-down tab only if a button is pressed that displays the direction between the user and the offer. In my _location.html.erb partial i:

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

(addresses are addresses)

Now this works great when partial mapping is done immediately. However, if I try to make a partial AJAX call later after the entire page is already loaded, gmap is not displayed. Is it possible to initialize and display gmap through an AJAX call and display directions?

+2
source share
1 answer

The reason is quite simple: partial contains a lot of javascript that you cannot load and execute in this way.

Therefore, you cannot use RJS there.

The correct way is UJS: get data with an AJAX call and display the result. In the following code, I am using jQuery.

In your opinion, 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 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 to your CSS:

 #map-container { width: 800px; } #gmaps4rails_map { width: 800px; height: 400px; } 
+2
source

All Articles