2011-06-17 36 views
2

有一些主題試圖在此處探討:Gmaps4rails : map not showing when loaded dynamically,特別是這裏:Rendering google map using gmaps4rails through Ajax,也觀看了gmap動態更新的屏幕錄像,但我似乎仍然無法獲取它工作。通過使用Gmaps4rails的AJAX調用來渲染Gmap

我想在下拉選項卡中加載地圖,只有在單擊按鈕時顯示用戶和報價之間的方向。在我_location.html.erb部分我有:

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

(位置是地址)

現在,這很好地工作在部分立即呈現。但是,如果我嘗試在整個頁面初始加載後稍後渲染AJAX調用的部分內容,則不會顯示gmap。是否有可能通過AJAX調用初始化和渲染gmap,然後顯示方向?

回答

2

原因很簡單:部分包含很多JavaScript,您無法加載並執行此操作。

所以你不能在那裏使用RJS。

正確的做法是UJS:使用AJAX調用獲取數據並呈現結果。在下面的代碼中,我使用jQuery。

在您的視圖中添加:

//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> 

添加下面的類在你的CSS:

#map-container { 
    width: 800px; 
} 

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

哇,感謝您的快速答覆!很棒!此外,gmaps4rails是一個非常棒的寶石,感謝所有的工作! – user753416 2011-06-18 10:30:05

+1

我沒有編輯權限,但CSS應該是#而不是。 bc他們是ID – kinet 2011-06-23 07:21:28

+0

@kinet:謝謝;) – apneadiving 2011-06-23 08:00:42