Markers Created via JSON Are Not Clustering with Google Maps MarkerClusterer

吃可爱长大的小学妹 提交于 2019-12-02 09:44:20

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 = '<p>' + cameras.cameralabel + '</p>';
                    html += '<img src="' + cameras.imageurl.url + '"/>';
                    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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!