与GeoJson一起使用的传单MarkerCluster

时间:2015-04-23 13:10:46

标签: json leaflet markerclusterer

我目前正在制作一个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 }

我做错了什么?

2 个答案:

答案 0 :(得分:3)

好吧,看起来你正在使用Leaflet-Ajax ...所以异步请求是为了抓住你的geojson ..而你的下一行是markersBar.addLayer(barLayer); ..自请求以来什么都不包含几乎肯定还没完成......

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

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

答案 1 :(得分:0)

对于任何正在寻找直接示例的人,将带有 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")
});