dongxie2749
dongxie2749
2013-08-13 21:55

Google Maps AP v3 I - 尝试使用jQuery $ .ajax动态添加标记

I am using the Google Maps API v3 to create a map for my application to show viewers on our Webcast. The idea is to add a new marker on the map when a new viewer jumps onto the stream. That is the map is not reloaded, only a new marker is added.

I am trying to accomplish this with an ajax call to a script that gets the current viewers. I have an output to the console to show the results, and the latitude and longitude coordinates are correct, so I don't know why it does not put the marker onto the map.

I am referencing the same class in the page with the map as I am with the ajax script call, so I can do a PHP foreach loop in the middle of the javascript on the page and it puts the marker onto the map! But, of course, I need to use ajax to get new serverside info (new viewers).

js with php foreach() (works)

note: this is how I tested it, it is in $.ajax success function, but has nothing to do with the ajax script

//add markers
function addMarker(stream_id) {
  $.ajax({
    dataType: 'json',
    url: '../../stream/' + stream_id + '/mapmarkers',
    success: function(result) {
      <?php foreach($stream_viewer_info as $viewer) : ?>

        markers.push(new google.maps.Marker({
          position: new google.maps.LatLng(<?= $viewer['location_info']['latitude'] . ', ' . $viewer['location_info']['longitude']; ?>),
          map: map
        }));

      <?php endforeach; ?>

    },
    complete: function() {
      setTimeout(function(){addMarker(<?=$stream_id; ?>)}, 1000);
    }


  });
}

js with js for() (does not work)

//add markers
function addMarker(stream_id) {
  $.ajax({
    dataType: 'json',
    url: '../../stream/' + stream_id + '/mapmarkers',
    success: function(result) {
      for(var i = 0; i < result.length; i++) {
          console.log('result ' + i + ': ' + result[i]['latitude'] + ', ' + result[i]['longitude']);

        markers.push(new google.maps.Marker({
          position: new google.maps.LatLng(result[i]['latitude'] + ', ' + result[i]['longitude']),
          map: map
        }));

      }

    },
    complete: function() {
      setTimeout(function(){addMarker(<?=$stream_id; ?>)}, 1000);
    }


  });
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douzhulv1699 douzhulv1699 8年前

    Try this

    markers.push(new google.maps.Marker({
        position: new google.maps.LatLng(result[i]['latitude'], result[i]['longitude']),
        map: map
    }));
    

    You need to separate the arguments by an actual comma, not a string

    点赞 评论 复制链接分享