Reputation: 442
I am trying to use Google Maps API without the gmaps4rails gem.
It's a normal application where each instance of the model is a marker, and I'd like that each marker would have it's own info window.
In this part of the code lies the problem:
var locations = [];
<% @listings.each do |l| %>
locations.push([<%=raw l.latitude%>, <%=raw l.longitude %>]);
<% end %>
The code works as is, but when I try to call a third object that is not a number (say <%=raw l.title %>
) the maps simply does not load. Moreover, any text inside Ruby will not load - say <%=raw "text" %>
or <%= "text" %>
while <%= 2 %>
does work.
How can I surpass this issue and call the ruby model to build an infowindow with? Is it JSON? If so, I would I use it?
Thanks in advance, Tiago
Map partial:
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(1.3, 103.85),
zoom: 12,
disableDefaultUI: true,
zoomControl:true
};
var locations = [];
<% @listings.each do |l| %>
locations.push([<%=raw l.latitude%>, <%=raw l.longitude %>]);
<% end %>
var map = new google.maps.Map(document.getElementById("index-map-canvas"),
mapOptions);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("<div>"+locations[i][2]+"</div>");
infowindow.open(map, marker);
}
})(marker, i));
};
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Controller:
def index
@q = Listing.search(params[:q])
@listings = @q.result(distinct: true).paginate(:page => params[:page], :per_page => 10)
end
Upvotes: 2
Views: 939
Reputation: 115511
Replace:
var locations = [];
<% @listings.each do |l| %>
locations.push([<%=raw l.latitude%>, <%=raw l.longitude %>]);
<% end %>
With:
var locations = <%= raw @listings.to_json %>;
Upvotes: 1