2016-07-04 4 views
2

Ich bin neu bei Schienen und ich frage mich, wie genau ich diese Marker loopen könnte. Meine JS-Variable "count" wird nicht erkannt und ich brauche Hilfe, um mein Ruby-Array zu durchlaufen oder eine andere Lösung zu benötigen.Looping von Google Maps-Markern mit eingebettetem Rubin?

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 %> 
+0

Mischen Sie Erbcode und Javascript ist ziemlich schlecht. Sie sollten die Markers-Informationen besser durch einen Ajax-Aufruf (wenn sie in db gespeichert sind) erhalten und sie in "Erfolg" -Antwort auffüllen – kasperite

Antwort

1

Wie Sie neu in Rails, kann ich diese Lösung vorschlagen:

1.Add eine Aktion 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. 
    }) 
} 

Das ist im Grunde, wie es funktionieren sollte. Passen Sie einfach den Code an, um Ihrem Bedarf zu entsprechen

Verwandte Themen