带有 GeoJson 的 Leaflet MarkerCluster

Leaflet MarkerCluster with GeoJson

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

<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' />

在没有聚类的情况下显示 json 层效果很好,但如果我尝试将其分配给聚类,则不会显示任何内容。

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);

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 }

我做错了什么?

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

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

barLayer.on('data:loaded', function () {
    markersBar.addLayer(barLayer);
    console.log(markersBar);
    map.addLayer(markersBar);
});

对于正在寻找使用 geojson ajax 将标记集群添加到地图、绑定弹出窗口并添加到图层控件的直接示例的任何人:

// pop-up function
function popUp(f, l) {
    var out = [];
    if (f.properties) {
        for (key in f.properties) {
            out.push(key + ": " + f.properties[key]);
        }
        l.bindPopup(out.join("<br />"));
    }
}

// add layer to map and layer control
function add_layer(layr, layr_name) {
    map.addLayer(layr);
    layerControl.addOverlay(layr, layr_name);
}

// fire ajax request
var points = new L.GeoJSON.AJAX("../data/points.geojson", { onEachFeature: popUp });

// create empty marker cluster group
var markers = L.markerClusterGroup()

// when geojson is loaded, add points to marker cluster group and add to map & layer control
points.on('data:loaded', function () {
    markers.addLayer(points);
    add_layer(markers, "Point Markers")
});