How to add markers to Google Maps after the map has already been loaded?
<p>I'm working on a simple phoneGap app - I'm pacing around my house to collect coordinates:</p>

<pre><code>var positions = [
  {lat:123.12313123, lng:123.123345131},
  {lat:123.12313123, lng:123.123345131}
]
</code></pre>

<p>I'm checking out the <a href="https://developers.google.com/maps/documentation/javascript/examples/marker-simple" rel="nofollow">documentation here</a> which works flawlessly. In that example, the script <code>defer async</code> from what I understand fires when <code>initMap()</code> is created. <code>initMap()</code> has one marker. This works flawlessly in my app, showing the marker in Straya.</p>

<p>First, I create the map:</p>

<pre><code>var map; // making it global

  function initMap() {
    var myLatLng = {lat: 39.909736, lng: -98.522109}; // center US

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 2,
      center: myLatLng
    });
  }
</code></pre>

<p>This draws the map. Now, I'd like to iterate through my coordinates like so:</p>

<pre><code>// Remember, the map has already loaded at this point
$(positions).each(function(i, item) {
          var marker = new google.maps.Marker({
            position: item,
            map: map,
            title: 'Route item ' + i
          });
        })
</code></pre>

<p>This doesn't work. I can't be running <code>initMap()</code> inside of a loop, and it doesn't work anyway. I can't run <code>initMap()</code> with a pre-set number of coordinates because I don't know what they are yet until I'm done. What am I doing wrong here?</p>