带有 GeoJson 的传单 MarkerCluster

elt*_*aco 3 json markerclusterer leaflet

我目前正在使用外部 geojson 文件作为数据输入的传单项目。由于 json 包含很多对象,我想使用MarkerCluster从 Mappbox 获得的插件:

<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v0.4.0/leaflet.markercluster.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v0.4.0/MarkerCluster.css' rel='stylesheet' />
<link href='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v0.4.0/MarkerCluster.Default.css' rel='stylesheet' />
Run Code Online (Sandbox Code Playgroud)

在没有集群的情况下显示 json-layer 工作得很好,但是如果我尝试将它分配给集群,则不会显示任何内容。

var markersBar = L.markerClusterGroup();        
var barLayer = new L.GeoJSON.AJAX("json/eat_drink/bar.geojson", {
    pointToLayer: function(feature, latlng) {
        var icon = L.icon({
                        iconSize: [27, 27],
                        iconAnchor: [13, 27],
                        popupAnchor:  [1, -24],
                        iconUrl: 'icon/' + feature.properties.amenity + '.png'
                        });
        return L.marker(latlng, {icon: icon})
    }, 
    onEachFeature: function(feature, layer) {
        layer.bindPopup(feature.properties.name + ': ' + feature.properties.opening_hours);
    }
});
markersBar.addLayer(barLayer);
console.log(markersBar);
map.addLayer(markersBar);
Run Code Online (Sandbox Code Playgroud)

console.log 输出让我假设没有对象,但我不明白为什么。

Object { options: Object, _featureGroup: Object, _leaflet_id: 24, _nonPointGroup: Object, _inZoomAnimation: 0, _needsClustering: Array[0], _needsRemoving: Array[0], _currentShownBounds: null, _queue: Array[0], _initHooksCalled: true }
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

snk*_*his 5

好吧,看起来您正在使用Leaflet-Ajax ......所以会发出一个异步请求来获取您的 geojson ..并且您的下一行是markersBar.addLayer(barLayer);..它不会包含任何内容,因为该请求几乎肯定还没有完成......

相反,我相信您可以使用文档中提供的加载事件,例如

barLayer.on('data:loaded', function () {
    markersBar.addLayer(barLayer);
    console.log(markersBar);
    map.addLayer(markersBar);
});
Run Code Online (Sandbox Code Playgroud)