繁体   English   中英

你如何使用gmaps4rails在Ruby on Rails中使用UJS发送ajax调用?

[英]How do you use gmaps4rails to send a an ajax call using UJS in Ruby on Rails?

我按照两个位置的示例进行了操作:

但他们都不行。 我也没有得到任何回报。 我目前在RoR 3.2.8中使用1.5.5版本的gmaps4rails。

show_map.js.erb

$('#map_container').show();
$('#map_container').html('<%= escape_javascript( gmaps({:last_map => false}) ) %>');
Gmaps.map = new Gmaps4RailsGoogle();

Gmaps.load_map = function() {
  Gmaps.map.map_options.maxZoom = 15;
  Gmaps.map.initialize();
  Gmaps.map.create_markers();
  Gmaps.map.adjustMapToBounds();
  Gmaps.map.markers = <%= @json %>;
  Gmaps.map.callback();
};
Gmaps.loadMaps();

users_controller.rb

  def show_map
    @user = User.first
    @json = @user.to_gmaps4rails
    respond_to do |format|
      format.js {}
    end
  end

show.html.haml

  = link_to "Map", show_map_path, :remote => true
  #map_container{:style => 'display:none;'}

谢谢你的帮助!

我和@persistence有同样的问题,我更喜欢在这个帖子中报告。 我试图先跟随wiki示例然后坚持@apneadiving评论并遵循你的要点,但我仍然遗漏了一些要点。 我将此代码放在我的控制器中:

events_controller

def index
    @json = Event.all.to_gmaps4rails do |event, marker|
        marker.title        event.title
        marker.infowindow   event.description
        marker.sidebar      'This is a side bar'
    end
    p @json
    respond_with @json
end

在我看来,我粘贴了要点的确切代码。 当我按下加载按钮时,我在控制台中检查我的json信息是否正常,但是由于Javascript错误导致地图未加载:

TypeError: Gmaps.map is undefined

我想我错过了地图的某种Javascript初始化?

更新时间05/11/2012:

这确实是问题所在。 结合gist和wiki示例中的javascript,我通过在视图中放入以下代码来完成这项工作:

index_view

<!-- create html + load js files but don't create map itself: will be done after ajax call -->
<%= gmaps({:last_map => false}) %>
<br/>

<!-- button to trigger ajax call -->
<button type="button" id="ajax">Load Map</button>

<script type="text/javascript" charset="utf-8">
$(function() {

    //hide the empty container
    $(".map_container").hide();

    // Map initialization
    Gmaps.map = new Gmaps4RailsGoogle();
    Gmaps.load_map = function() {
         Gmaps.map.map_options.maxZoom = 15;
         Gmaps.map.initialize();
         Gmaps.map.create_markers();
         Gmaps.map.adjustMapToBounds();
         Gmaps.map.callback();
    };

    $("#ajax").click(function(){
         $.getJSON('/events', function(json){
              $(".map_container").show();
              Gmaps.loadMaps();
              Gmaps.map.addMarkers(json);
         })
    })
});
</script>

我还留下了一些在GitHub中加载Gmaps4Rails映射的简单示例: https//github.com/daviddefco/Gmaps4RailsS​​amples.git

  1. 使用和HTML部分
  2. 使用由HTML按钮触发的AJAX请求(主题示例)
  3. 在Javascript操作中使用AJAX请求(wiki示例)

我是一个RoR和Javascript新手,所以欢迎评论或代码改进。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM