Reputation: 21
I'm new to rails and I'm wondering how exactly I could loop these markers. My JS variable "count" is not recognized and I need some help looping through my ruby array or need another solution.
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 44.540, lng: -78.546},
zoom: 8
});
var total = <%= mapcount %>
var javascriptcount = 0;
var count = 0;
<% arraylat = [] %>
<% arraylng = [] %>
<% mapposttotal.each do |q| %>
<% arraylat << q.lat %>
<% arraylng << q.lng %>
<% end %>
for (; javascriptcount <= total; javascriptcount++) {
var marker = new google.maps.Marker({
position: {lat: <%= arraylat[count] %>, lng: <%= arraylng[count] %>},
map: map,
title: 'Hello World!'
});
count = count + 1;
console.log()
}
var Clicker = document.getElementById('PostIt');
Clicker.addEventListener('click', function() {
window.location='/newpost.html';}, false);
}
<% end %>
Upvotes: 2
Views: 73
Reputation: 2478
As you are new to Rails, I can suggest this solution:
1.Add an action in MarkersController
:
def index
respond_to do |format|
format.json do
markers = Marker.all.map do |marker|
{
lat: marker.lat,
lng: marker.lng
}
end
render json: markers
end
end
end
2.In routes.rb
get "/markers", to: "markers#index"
3.Javascript:
function initMap() {
$.getJSON("/markers", function(data) {
// All your js code to populate markers go in here.
})
}
That's basically how it should work. Just tailor the code to suit your need
Upvotes: 1