0

I am using Leaflet to add markers to map. The following ling of code is how the markers get added to my map.

markers.addLayer(new L.Marker([LAT, LONG]).bindPopup(POPUP).openPopup());

Now, LAT (float), LONG(float), and POPUP(string) are all data that are held in my database, in a companies table. So I want to loop through every row in this table and pull these three attributes from each row, add a marker and move on to the next.

I have looked up a few things, and I figured this would be a pretty good start, but I am sure how to alter this to fit my needs.

EDIT: It might be worth mentioning, that this is all done on page load and not with any click or anything of that nature.

1 Answer 1

1

There's various ways you could do this. The simplest is to just call that line of code repeatedly in your view.

#in some_template.html.erb - expects @companies to have been defined in the controller action.
<%= javascript_tag do %>
  (function() {
     <% @companies.each do |company| %>
       markers.addLayer(new L.Marker([<%= company.lat %>, <%= company.long %>]).bindPopup(<%= company.popup %>).openPopup());
     <% end %>
  })();      
<% end %>

You might need to tweak the formatting a bit.

Sign up to request clarification or add additional context in comments.

3 Comments

How exactly does @company need to be defined in the controller?
Currently I am getting the following error when I plug this into my view, undefined method each' for nil:NilClass`
Yes, sorry, i should have said. My code expects you to have defined @companies (not @company) in your controller. To get all of them, do @companies = Company.all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.