首页 > 解决方案 > 标记集群不起作用

问题描述

我用标记制作了谷歌地图,但我有很多标记所以想添加标记cluterer,但它似乎不起作用。在控制台中显示“未定义标记”。

var urlApi = "https://api.jcdecaux.com/vls/v1/stations?contract=lyon&apiKey=";


function initMap(){

  //map options
      var options ={
          zoom:13,
          center:{lat:45.7563172, lng:4.827523}
      }

  //new map
      var map = new google.maps.Map(document.getElementById('map'),options);
  //new markers
  $.getJSON(urlApi, function(data) {
      data.forEach(function(item) {
        var marker = new google.maps.Marker({
          position : {
              lat : parseFloat(item.position.lat),  
              lng : parseFloat (item.position.lng)

          },
          map:map
        })
      })
    });
    var markerCluster = new MarkerClusterer(map, marker,
      {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=&callback=initMap"></script>
  <script src="animation-fleche.js"></script>
  <script src="slider.js"></script>
  <script src="script.js"></script>
  <script src="map.js"></script>
</body>

标签: javascripthtmljson

解决方案


您创建标记,但不会将它们保存在任何地方。您需要创建一个 Marker 数组,然后将其传递给 MarkerCluster 构造函数:

$.getJSON(urlApi, function(data) {
  const markerArray = data.map(function(item) {
    return new google.maps.Marker({
      position : {
          lat : parseFloat(item.position.lat),  
          lng : parseFloat (item.position.lng)
      });
  });
  var markerCluster = new MarkerClusterer(map, markerArray,
  {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});

});

推荐阅读