Маркерный кластер не работает

1

Я пытаюсь реализовать кластер маркеров, поскольку приведенный ниже код не работает. Когда я пытаюсь выполнить это, он отображает маркер, но это не кластеризация маркеров. Я попытался исправить это, но я потерпел неудачу. Может ли кто-нибудь помочь мне решить эту проблему?

В приведенном ниже коде Var records хранят записи с значениями широты и долготы

<html>
    <style>
      #map {
        height: 100%;
      }
    </style>

<body>

   <div id="map" style="width:100%;height:700px"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
    </script>

    <script> 
function myMap() {
        var myCenter = new google.maps.LatLng(12.9715987,77.5945627);
        var mapCanvas = document.getElementById("map");
        var mapOptions = {center: myCenter, zoom: 2};
 //some code is there to fetch the records
      var  records = result.getArray("records");// it has records with latitude and longitude values

     for (var i=0; i< records.length; i++) {
              var record = records[i];
         console.log(record.Name + " -- " + record.Id+" -- "+record.Latitude);

           var markers = [];
            var marker = new google.maps.Marker({
                     position: new google.maps.LatLng(record.Latitude,record.Longitude),
                     map : map,
                    //icon: 'brown_markerA.png'
                    icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'

                });
          markers.push(marker);

                     var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
              } 
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=myMap"></script>
</body>
</html>
  • 0
    Я получаю ошибки javascript с опубликованным кодом (после исправления Uncaught ReferenceError: result is not defined ), js?libraries=geometry,places&ext=.js:40 InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama Uncaught TypeError: this.map_.getZoom is not a function . В вашем коде нет google.maps.Map ...
Теги:
google-maps

1 ответ

1
Лучший ответ

У вас есть несколько опечаток в вашем коде:

  1. У вас нет переменной google.maps.Map
var map = new google.maps.Map(mapCanvas, mapOptions);
  1. Вы создаете пустой пул внутри цикла, перемещаете его снаружи.
var markers = [];
// start of loop
for (var i = 0; i < records.length; i++) {
  1. Вы создаете MarkerClusterer для каждого маркера (внутри цикла), переместите его за пределы цикла:
} // end of loop
var markerCluster = new MarkerClusterer(map, markers, {
  imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});

доказательство концепции скрипки

фрагмент кода:

function myMap() {
  var myCenter = new google.maps.LatLng(12.9715987, 77.5945627);
  var mapCanvas = document.getElementById("map");
  var mapOptions = {
    center: myCenter,
    zoom: 2
  };
  var map = new google.maps.Map(mapCanvas, mapOptions);
  //some code is there to fetch the records
  var records = [{Latitude: 12.9715, Longitude: 77.5945627},{Latitude: 12.97159, Longitude: 77.594},{Latitude: 12.9715987, Longitude: 77.5945627},{Latitude: 12.971, Longitude: 77.5945627},{Latitude: 12.97, Longitude: 77.5945627}];
  var markers = [];
  for (var i = 0; i < records.length; i++) {
    var record = records[i];
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(record.Latitude, record.Longitude),
      map: map,
      //icon: 'brown_markerA.png'
      icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
    });
    markers.push(marker);
  }
  var markerCluster = new MarkerClusterer(map, markers, {
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
  });
}
google.maps.event.addDomListener(window, "load", myMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<div id="map"></div>
  • 0
    Большое спасибо, после устранения вышеуказанных проблем. это работает

Ещё вопросы

Сообщество Overcoder
Наверх
Меню