简体   繁体   中英

Removing old markers and Polylines before adding new ones - Mapbox

Given the following code for Mapbox, whereby I am plotting points and polylines between a number of points. User will choose a different selection and the results of that will replace the pins on the map. These pins will then be drawn together in the correct order using polylines.

$.post('_posts/get-pins.php', {traveller: $(this).val()}, function(data){

var featureLayer = L.mapbox.featureLayer().addTo(map);

var featureCollection = {
    "type": "FeatureCollection",
    "features": []
};

var lineArray = [];

$.each(data, function (k, item) {
    featureCollection.features.push({
        "type": "Feature",
        "properties": {
            "id": item.id,
            "title": item.title,
            "description": item.description,
            "image": item.image,
            "marker-symbol": "star",
            "marker-color": "#ff8888",
            "marker-size": "large"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [
                item.long,
                item.lat
            ]
        }
    });

    lineArray[item.id] = [item.lat, item.long];
});

featureLayer.setGeoJSON(featureCollection);

lineArray = lineArray.filter(function(){return true});


var polyline = L.polyline(lineArray).addTo(map);

},'json');

So I need to remove the polylines and the markers before plotting the new ones. I have tried numerous combinations of map.removeLayer(xxx) replacing xxx with many of the variables that are being created but all I have managed to do is remove the markers. It just leaves the polylines intact and just stacks the polyline layers.

Declare your variables for the featureLayer and polyline outside of the method/function you are using to update them:

var featureLayer, polyline;

In the function, check if the variable featureLayer already is an instance of FeatureLayer then clear it's layers, if it's not create the new layer:

if (featureLayer instanceof L.mapbox.FeatureLayer) {
    featureLayer.clearLayers();
} else {
    featureLayer = L.mapbox.featureLayer().addTo(map);
}

With the polyline you got to do it differently because it hasn't got a function to clear al the added points, just check if it's an instance of L.Polyline, if so remove it from the map using L.Map's removeLayer method and afterwards just define a new polyline:

if (polyline instanceof L.Polyline) {
    map.removeLayer(polyline);
}

polyline = L.polyline([]).addTo(map);

Working example on Plunker: http://plnkr.co/edit/7nlgiA50NuPGsQOF0Fv4?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM