如何通过 GeoJSON 将标记添加到现有层,而无需重置它

How to add markers via GeoJSON to an existing layer, without having to reset it

我正在使用 mapbox

我有一个图层包含我的标记:

 map = L.mapbox.map(id, map_id...)
 map.featureLayer # this is the layer containing all my markers

我想要的是在不删除现有标记的情况下向该层添加标记。但是我不想仅仅通过 L.mapbox.Marker 创建一个标记,我想通过 GeoJSON 添加它们,因为我想向它添加自定义属性。

我尝试创建一个新的 featureLayer,通过 setGeoJSON 添加我的新标记的 GeoJSON,然后将此图层添加到现有图层。如果我这样做,我的自定义过滤器 (setFilter) 将不会应用于该子层。

另一个想法是创建另一个图层,通过 setGeoJSON 添加 json,然后遍历其标记并将它们添加到现有的 featureLayer。有这个可能吗?

如何通过 GeoJSON 添加标记到现有图层?

您可以尝试这样的事情,它取决于从 L.LayerGroup 继承的两个函数,称为 removeLayer & addLayer:

// Create featurelayer and add it to the map
var featureLayer1 = L.mapbox.featureLayer(mapid).addTo(map);

// Create another featurelayer, don't add it to the map
var featureLayer2 = L.mapbox.featureLayer(mapid);

// Wait until ready
featureLayer2.on('ready', function () {
    // Loop over the layers in the layer
    featureLayer2.eachLayer(function (layer) {
        // Remove them from this layer, this is important because a layer
        // (marker, polygon etc) can't be present in two layers at once
        featureLayer2.removeLayer(layer);
        // Add them to the other layer
        featureLayer1.addLayer(layer);
    }
});

就我个人而言,我将其称为快速破解。我宁愿使用 L.GeoJSON ,它有一个 addData 方法,它可以添加功能或功能集合而不删除已经添加的功能。

// Creates empty GeoJSON layer
var geojson = L.geoJson().addTo(map);

// Creates GeoJSON layer with initial data
var geojson = L.geoJson(geojsonObject).addTo(map);

// Add data afterwards
geojson.addData(geojsonObject);

我无法从您获取初始数据的代码中弥补,如果它是来自 mapbox 地图的要素,您可以像这样加载它们:

// Create a featureLayer which loads your features
var featureLayer = L.mapbox.featureLayer('examples.map-zr0njcqy');

// Create empty geojson layer
var geojsonLayer = L.geoJson().addTo(map); 

// Wait until everything is loaded 
featureLayer.on('ready', function() {
    // Turn layer's features back into geojson
    var features = featureLayer.getGeoJSON();
    // Add features to geojsonLayer
    geojsonLayer.addData(features);
});

// Now you can add more data afterwards
geojsonLayer.addData(moreFeatures);

您也可以使用 jQuery 的单个请求来获取它们,例如:

$.getJSON('http://a.tiles.mapbox.com/v4/MAPID/features.json?access_token=TOKEN', function (data) {
    geojson.addData(data);
});

您可以使用与 L.GeoJSON 几乎相同的方式进行过滤:

L.geoJSON(data, {
    'filter': function (feature) {
        //return true or false
    }
}).addTo(map);

参考:http://leafletjs.com/reference.html#geojson

教程:http://leafletjs.com/examples/geojson.html

通常我会在 Plunker 上创建一个示例来演示,但它们今天已关闭,所以我无法创建测试用例。上面的代码是从记忆中快速完成的吗,无法测试,所以如果我犯了任何错误,请原谅我。