Markers Created via JSON Are Not Clustering with Google Maps MarkerClusterer

前端 未结 1 1383
忘掉有多难
忘掉有多难 2021-01-27 13:56

I\'m having trouble getting the Google Maps MarkerClusterer to work. I\'m fairly sure I follow procedure correctly (i.e. creating the map, adding markers to an array, not settin

1条回答
  •  独厮守ぢ
    2021-01-27 14:16

    You need to initialize the MarkerClusterer inside the callback function (where the markers array is created).

    $('document').ready(function() {
    
        $('#map').height($(window).height() - $('#map').position().top - 20);
    
        var mapElem = document.getElementById('map');
    
        var center = {
            lat: 47.6,
            lng: -122.3
        }
    
        var map = new google.maps.Map(mapElem, {
            center: center,
            zoom: 12
        });
    
        var infoWindow = new google.maps.InfoWindow();
        var cameras;
        var markers = [];
    
        $.getJSON('http://data.seattle.gov/resource/65fc-btcc.json')
            .done(function(data) {
                cameras = data;
                cameras.forEach(function(cameras) {
                    var marker = new google.maps.Marker({
                        position: {
                            lat: parseFloat(cameras.location.latitude),
                            lng: parseFloat(cameras.location.longitude)
                        }
                    });
    
                    google.maps.event.addListener(marker, 'click', function() {
                        map.panTo(this.getPosition());
                        var html = '

    ' + cameras.cameralabel + '

    '; html += ''; infoWindow.setContent(html); infoWindow.open(map, this); }); google.maps.event.addListener(map, 'click', function() { infoWindow.close(); }); markers.push(marker); $('#search').bind('search keyup', function() { var cameraName = cameras.cameralabel.toLowerCase(); var searchString = this.value.toLowerCase(); if (cameraName.indexOf(searchString) < 0) { marker.setMap(null); } else { marker.setMap(map); } }); }); // here, inside the .done function var markerCluster = new MarkerClusterer(map, markers); }) .fail(function(err) { console.log(err); alert('Sorry, unfortunately something went wrong!'); }); $(window).resize(function() { $('#map').height($(window).height() - $('#map').position().top - 20); }); });

    working fiddle

    0 讨论(0)
提交回复
热议问题