Google Maps API - 仅显示第一个标记的标记数组

时间:2014-09-15 12:04:34

标签: javascript google-maps google-maps-api-3

我刚开始使用Google Maps API,并尝试在数据数组中显示多个标记。

但是我在列表中的第一个位置得到一个标记,我想这意味着我的循环不能正常工作,但我没有得到任何错误。

    var mapOptions = {
        center: centralLatlng,
        zoom: 2
    };

    var map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);

    var cdnLocations = [
        ['LondonMarker', 51.500, 0.1167],
        ['NewYorkMarker', 40.7127, -74.0059],
        ['TokyoMarker', 35.6895, 139.6917],
        ['BerlinMarker', 52.5167, 13.3833],
        ['ParisMarker', 48.8567, 2.3508],
        ['MadridMarker', 40.4000, 3.6833],
    ]


    for (var i = 0; i < cdnLocations.length; i++) {
        var cdnLocations = cdnLocations [i]
        var marker = new google.maps.Marker({
        position: new google.maps.LatLng (cdnLocations[1], cdnLocations[2]),
        map: map,

    });
    }

1 个答案:

答案 0 :(得分:1)

检查出来:

<!DOCTYPE html>
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
<title>Google Maps Multiple Markers</title> 
<script src="http://maps.google.com/maps/api/js?sensor=false" 
      type="text/javascript"></script>
</head> 
<body>
<div id="map" style="width: 500px; height: 400px;"></div>

<script type="text/javascript">
var locations = [
    ['LondonMarker', 51.500, 0.1167],
    ['NewYorkMarker', 40.7127, -74.0059],
    ['TokyoMarker', 35.6895, 139.6917],
    ['BerlinMarker', 52.5167, 13.3833],
    ['ParisMarker', 48.8567, 2.3508],
    ['MadridMarker', 40.4000, 3.6833],
];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 1,
  center: new google.maps.LatLng(35.68, 139.69),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

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][1], locations[i][2]),
    map: map
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}
</script>
</body>
</html>

这是一个jsfiddle示例: http://jsfiddle.net/m2htynto/