2015-04-23 40 views
2

我目前正在使用外部geojson文件作爲數據輸入的Leaflet項目。由於JSON中包含了大量的對象,我想用MarkerCluster插件,這是我從Mappbox有:傳單MarkerCluster與GeoJson

<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 } 

我在做什麼錯?

回答

3

好吧,它看起來像你使用Leaflet-Ajax ...所以一個異步請求,以獲取您的geojson..and你的直接下一行是markersBar.addLayer(barLayer); ..哪些不包含任何東西,因爲請求幾乎肯定還沒有完成。 ..

相反,我相信你可以使用在documentation提供的加載事件像

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

哇,那沒有的伎倆!非常感謝@snkashis – eltomaco

+0

這工作,但腳本缺少a);在最後。 – MarsAndBack