TypeError marker.getPosition不是函数

时间:2019-07-02 09:37:03

标签: javascript google-maps google-maps-markers markerclusterer

您好,我在运行以下代码时收到错误消息。我在哪里犯错? 如果您有帮助,我将不胜感激 预先感谢

错误:TypeError:marker.getPosition不是函数

function initMap() {
var locations = [
      ['Bondi<br>Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
    ];

var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();
var markers, i;
for (i = 0; i < locations.length; i++) {  
      var markers = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(markers, 'click', (function(markers, is) {
        return function() {
          infowindow.setContent(locations[is][0]);
          infowindow.open(map, markers);
        }
      })(markers, i));

      var markerCluster = new MarkerClusterer(map, markers,{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
    }
}
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=xxx&callback=initMap"></script>

1 个答案:

答案 0 :(得分:0)

尝试以下修改后的代码:

  function initMap() {
    var locations = [
      ["Bondi<br>Beach", -33.890542, 151.274856, 4],
      ["Coogee Beach", -33.923036, 151.259052, 5]
    ];

    var map = new google.maps.Map(document.getElementById("map"), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();
    var markers, i;
    for (i = 0; i < locations.length; i++) {
      var markers = locations.map(function(location, i) {
        var 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, is) {
            return function() {
              infowindow.setContent(locations[is][0]);
              infowindow.open(map, marker);
            };
          })(marker, i)
        );

        return marker;
      });

      var markerCluster = new MarkerClusterer(map, markers, {
        imagePath:
          "https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m"
      });
    }
  }

我建议您仔细阅读Google的文档,以了解如何正确添加带有标记簇的Google地图: https://developers.google.com/maps/documentation/javascript/marker-clustering

希望这会有所帮助!