leaflet geoJSON.onEachFeature 不是函数?

leaflet geoJSON.onEachFeature is not a function?

我正在尝试使用一系列点弹出窗口实现一个 "Add to Cart" 模型(您单击一个点,然后有一个按钮显示 "Add to Cart",它将弹出窗口中的信息添加到单独的 ul 标签。

我有以下有效的代码,但返回未定义的值:

        var content = [];

        //create popups
        function onEachPopup(feature, layer) {
            layer.bindPopup("<button type='button' onclick = 'addToCart(" + layer._leaflet_id + 
                            ")'>Add to Cart</button>")
        };

        //create geoJSON
        geojson = L.geoJSON(pointfixed, {
        pointToLayer: function (feature, latlng){
            return L.circleMarker(latlng, {
                radius: 3,
                fillColor: getColor(feature.properties.Coordinate),
                color: "#000",
                fillOpacity: 1,
                weight: 1
                }); 
        },
            onEachFeature : onEachPopup, function(feature, layer){feature.layer=layer}
        }).addTo(map);

        //add to cart function
        function addToCart(i){
            content.push(geojson._layers[i])
            content.forEach(function (c){
            document.getElementById("cartlist").innerHTML += '<li>' + content + '</li>' 
        })
        };

这有效,但是 returns 值未定义。

我认为我的 geojson 创建存在时间问题,所以我尝试稍微移动一下,如下所示:

        geojson = L.geoJSON(pointfixed, {
        pointToLayer: function (feature, latlng){
            return L.circleMarker(latlng, {
                radius: 3,
                fillColor: getColor(feature.properties.Coordinate),
                color: "#000",
                fillOpacity: 1,
                weight: 1
                }); 
        },
        }).addTo(map);
    geojson.onEachFeature(onEachPopup);

这会导致弹出窗口出现问题(它们不显示)并且出现以下错误: 未捕获的类型错误:geojson.onEachFeature 不是函数

我对传单还是很陌生,很难确定问题出在哪里。有什么明显的我想念的吗?

您未定义是因为您的图层没有 leaflet_id,因为该图层尚未添加到地图中。

将您的代码更改为:

geojson = L.geoJSON(pointfixed, {
        pointToLayer: function (feature, latlng){
            return L.circleMarker(latlng, {
                radius: 3,
                fillColor: getColor(feature.properties.Coordinate),
                color: "#000",
                fillOpacity: 1,
                weight: 1
                }); 
        },
}).addTo(map);

geojson.eachLayer(function(layer){
     layer.bindPopup("<button type='button' onclick = 'addToCart(" + layer._leaflet_id +")'>Add to Cart</button>");
});