How to get the id field and send to the view

2019-07-31 11:02发布

I'd like to know how can I get the ID field from my Model to pass in the JavaScript that I call when I click in a marker.

My model:

acts_as_gmappable :process_geocoding => false, :lat => "lat", :lng => "lon"

My controller

def index
    @locales_markers = Locale.all.to_gmaps4rails
    respond_to do |format|
      format.html  { render :layout => false }
    end
end

My View

<%= gmaps("markers" => { "data" => @locales_markers } %>

<% content_for :scripts do %>
    <script>
        Gmaps4Rails.callback = function() {
            for (var i = 0; i <  this.markers.length; ++i) {
                google.maps.event.addListener(Gmaps4Rails.markers[i].serviceObject, 'click', function(){
                    $('#info').load('/messages/' **<HERE I'D LIKE TO PASS THE ID>**);
                    $('#info').dialog("open");
                });

            }
        };
    </script>
<% end %>

Thanks, Luciano

2条回答
萌系小妹纸
2楼-- · 2019-07-31 11:22

Every marker property is stored and can be retrieved.

In your example, simply do:

$('#info').load('/messages/' + Gmaps4Rails.markers[i].id );

EDIT:

You should create another js function:

custom_listener = function(the_id) {
  return function(){
        $('#info').load('/messages/' + the_id );
        $('#info').dialog("open");
  };
};

And call it this way:

Gmaps4Rails.callback = function() {
 for (var i = 0; i <  this.markers.length; ++i) {
     google.maps.event.addListener(Gmaps4Rails.markers[i].serviceObject, 'click', custom_listener(Gmaps4Rails.markers[i].id));
  }
};
查看更多
姐就是有狂的资本
3楼-- · 2019-07-31 11:44

I changed my controller to:

  def index
    @locales_markers = Locale.all.to_gmaps4rails do |locale|
      "\"id\": \"#{locale.id}\""
    end
    respond_to do |format|
      format.html  { render :layout => false }
    end
  end

and work fine, but, I'm not able to get the id value in the view.

How to solve it?

Thanks, Luciano

查看更多
登录 后发表回答