title: Using JSON Data to Populate a Google Map with Database Objects
body: <p>I'm revising this question after reading the resources mentioned in the original answers and working through implementing it.   </p>
  
  <p>I'm using the google maps api to integrate a map into my Rails site. I have a markets model with the following columns: ID, name, address, lat, lng.  </p>
  
  <p>On my markets/index view, I want to populate a map with all the markets in my markets table.  I'm trying to output @markets as json data, and that's where I'm running into problems.  I have the basic map displaying, but right now it's just a blank map.  I'm following the tutorials very closely, but I can't get the markers to generate dynamically from the json.  Any help is much appreciated!</p>
  
  <p>Here's my setup:  </p>
  
  <p>Markets Controller: </p>
  
  <pre><code>def index
     @markets = Market.filter_city(params[:filter])
       respond_to do |format|
       format.html # index.html.erb
       format.json { render :json =&gt; @market}
       format.xml  { render :xml =&gt; @market }
    end
  end
  </code></pre>
  
  <p>Markets/index view:    </p>
  
  <pre><code>&lt;head&gt;
      &lt;script type="text/javascript"
        src="http://www.google.com/jsapi?key=GOOGLE KEY REDACTED, BUT IT'S THERE" &gt;
  &lt;/script&gt;
  &lt;script type="text/javascript"&gt;
      var markets = &lt;%= @markets.to_json %&gt;;
  &lt;/script&gt;
  &lt;script type="text/javascript" charset="utf-8"&gt;
      google.load("maps", "2.x");
      google.load("jquery", "1.3.2");
    &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;    
      &lt;div id="map" style="width:400px; height:300px;"&gt;&lt;/div&gt; 
  &lt;/body&gt;    
  </code></pre>
  
  <p>Public/javascripts/application.js:  </p>
  
  <pre><code>function initialize() {   
    if (GBrowserIsCompatible() &amp;&amp; typeof markets != 'undefined') {
      var map = new GMap2(document.getElementById("map"));
      map.setCenter(new GLatLng(40.7371, -73.9903), 13);
      map.addControl(new GLargeMapControl());
  
  function createMarker(latlng, market) {
    var marker = new GMarker(latlng);
    var html="&lt;strong&gt;"+market.name+"&lt;/strong&gt;&lt;br /&gt;"+market.address;
    GEvent.addListener(marker,"click", function() {
      map.openInfoWindowHtml(latlng, html);
    });
    return marker;
  }
  
  var bounds = new GLatLngBounds;
  for (var i = 0; i &lt; markets.length; i++) {
    var latlng=new GLatLng(markets[i].lat,markets[i].lng)
    bounds.extend(latlng);
    map.addOverlay(createMarker(latlng, markets[i]));
  }
  </code></pre>
  
  <p>}
  }  </p>
  
  <pre><code>window.onload=initialize;  
  window.onunload=GUnload;    
  </code></pre>