首页 > 解决方案 > Leaflet marker.cluster 弹出传单ajax加载的geojson数据

问题描述

我想创建一个传单地图来显示站点位置。站点数据leaflet ajax以 geojson 格式加载。

然后我Leaflet.markercluster用来创建一个集群视图,它工作正常。但似乎弹出窗口只显示最后一个站点,无论我点击哪个图标。

这是我的原始代码

function map_viewer(map, options){

        var my_data = new L.GeoJSON.AJAX("http://127.0.0.1:8000/my_data/",{
            onEachFeature: function(feature,layer){
            layer.bindPopup(feature.properties.siteid);

            clusters.on('click', function (e) {              
            this.bindPopup(feature.properties.siteid); 
            });
            }

        });

        var clusters = L.markerClusterGroup();
        my_data.on('data:loaded', function() 
        {
        clusters.addLayer(my_data);
        map.addLayer(clusters);
        });
        
        

        var groupedOverlays = {
          "Layers": {
            "cluster view":  clusters   
          }
        };

        L.control.groupedLayers(groupedOverlays).addTo(map);
    }

2021-02-01 更新:

我在谷歌上搜索后发现有一些类似的案例。但是,当我根据建议优化代码时,弹出窗口不再出现:

    function map_viewer(map, options){
            var clusters = L.markerClusterGroup();
            var my_data = new L.GeoJSON.AJAX("http://127.0.0.1:8000/my_data/",{
                onEachFeature: function(feature,layer){
                layer.bindPopup(feature.properties.siteid);
                }
    
            });
    
            my_data.on('data:loaded', function() 
            {
            clusters.addLayer(my_data);
            map.addLayer(clusters);
            });
    
        }

另外,请参考下面导入geojson数据集的一小部分。

{"type": "FeatureCollection", "crs": 
{"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [
{"type": "Feature", "properties": {"siteid": 1, "latitude": -28.004959, "longitude": 153.428117, "pk": "1"}, "geometry": {"type": "MultiPoint", "coordinates": [[153.428117, -28.004959]]}}, 
{"type": "Feature", "properties": {"siteid": 2, "latitude": -33.870436, "longitude": 151.225013, "pk": "2"}, "geometry": {"type": "MultiPoint", "coordinates": [[151.225013, -33.870436]]}}, 
{"type": "Feature", "properties": {"siteid": 3, "latitude": -33.92677, "longitude": 151.21356, "pk": "3"}, "geometry": {"type": "MultiPoint", "coordinates": [[151.21356, -33.92677]]}}, 
{"type": "Feature", "properties": {"siteid": 4, "latitude": -33.854711, "longitude": 150.987657, "pk": "4"}, "geometry": {"type": "MultiPoint", "coordinates": [[150.987657, -33.854711]]}}, 

结论:

我只是通过将我的 geojson 数据集中的几何类型从“多点”转换为“点”来解决这个问题。看来这个插件Leaflet.markercluster只能对Multipoints进行集群视图,但不能显示每一层的bindPopup。

标签: leafletleaflet.markercluster

解决方案


我很清楚为什么弹出窗口具有最后一个 id,因为在onEachFeature函数中,每次弹出窗口都使用新的 siteid 绑定/覆盖到集群,因此应用了最后一个。

但是,当您将弹出窗口添加到完整的标记集群时,所有图层都具有相同的弹出窗口。因此,将您的代码更改为:

        var my_data = new L.GeoJSON.AJAX("http://127.0.0.1:8000/my_data/",{
            onEachFeature: function(feature,layer){
               layer.bindPopup(feature.properties.siteid);
            }

        });

推荐阅读