2

I've attached a sample of my code below.

What I'm trying to do here, is be able to select a csv file to display their markers. What happens currently, is that it doesn't delete the old markers/polylines etc.

How would I be able to clear the map of any lines and markers/points etc?

I've attempted the removeLayers() function however it stops drawing any markers on the map.

    function openFile(afile){
        //points = coord info from csv
        var points = omnivore.csv(afile)
        //once it loads
        .on('ready', function() {
            //console.log(filename);
            //place markers and for each marker perform the below operations
            map.fitBounds(points.getBounds());
            points.eachLayer(function(layer){
                // TODO: validate headers (make sure the CSV headers are exactly as expected)
                // set priority images
                if(layer.feature.properties.priority == 'high'){
                    layer.setIcon(highIcon);
                }
                else if(layer.feature.properties.priority == 'extreme'){
                    layer.setIcon(extremeIcon);
                }
                else if(layer.feature.properties.priority == 'moderate'){
                    layer.setIcon(moderateIcon);
                }
                // create a new point & add to the manager
                p = new Point(
                        layer.feature.geometry.coordinates[1], // lat
                        layer.feature.geometry.coordinates[0], // long
                        layer.feature.properties.type, //type of faul
                        layer.feature.properties.priority, //priority of fault
                        layer.feature.properties.meme, // date
                        layer.feature.properties.time, //time
                        layer.feature.properties.timeDif, //timeDifference
                        layer.feature.properties.totalTime, //total time
                        layer.feature.properties.video //video name
                    );
                //for each layer(marker), add point to the PointManager array
                PointManager.addPoint(p);

                //Display basic infomation in popup + button for more info
                layer.bindPopup(
                    "Type of fault: " +
                     p.getType() + 
                     "<br> Priority :" + 
                     p.getPriority() + 
                     "<br>" +
                     "<button id='button' onclick='displayInfo("+p.getLat()+","+p.getLong()+")'> More info</button>");

                latlngs.push(layer.getLatLng());
            });
            //This displays the blue line going from marker to marker
            line = L.polyline(latlngs, {color: "blue", 
                showMeasurements : true, 
                measurementOptions :{minDistance : 0}
            }).addTo(map);

            //configuration for the moving train marker
            //params: coordinates, duration (1000 = 1 second), autostart = run on load, loop = repeat after finishing, icon = custom icon
            myMovingMarker = L.Marker.movingMarker(latlngs, 20000, {autostart : false, loop : false, icon : trainIcon}).addTo(map);

            //------------------------------------------------------------------------------  
            //COMPLETE
            //function to control the marker, so you can pause it and start it. Once marker reaches destination, clicking on it reset it
            myMovingMarker.once('click', function(){
                myMovingMarker.start();
                myMovingMarker.closePopup();
                myMovingMarker.unbindPopup();
                myMovingMarker.on('click', function() {
                    if(myMovingMarker.isRunning()){
                        myMovingMarker.pause();
                    }
                    else{
                        myMovingMarker.start();
                    }
                    if(myMovingMarker.isEnded()){
                        myMovingMarker.resume();
                    }
                });
                setTimeout(function(){
                    myMovingMarker.bindPopup('<b>Click to pause</b>').openPopup();
                }, 2000);
            });

            myMovingMarker.bindPopup('<b>Click me to start</b>', {closeOnClick: true});
            myMovingMarker.openPopup();
            //------------------------------------------------------------------------------ 
            //plugin for compressing markers into clusters based on radius
            markers = L.markerClusterGroup({
                showCoverageOnHover: true,
                maxClusterRadius: 25
            });
            //Add layers on the map for markers(cluster), map and points
            markers.addLayer(points);
            map.addLayer(markers);
            points.eachLayer(eachLayer);

        }).addTo(map); 
    }

EDIT: The issue I'm having is removing all layers in the beginning. The idea of the code sample above is that upon selecting a file, it loads the map and markers and displays them. In current form, the markers just keep loading over one another. What I am aiming for, is to remove previous markers each time the openFile function is executed.

3
  • 2
    Use map.removeLayer(your_layer); and your_layer.clearLayers(); before inserting the new one.
    – GeoGyro
    Commented Feb 6, 2018 at 15:26
  • 1
    @GeoGyro is there a method for removing all layers without providing names & not removing the map layer? In my case, I have to clear everything in the beginning of the function "openFile" (otherwise it clears everything as soon as I open a file) Edit: Thank you for your answer, btw! Commented Feb 8, 2018 at 1:16
  • 1
    You can try this method map.eachLayer(function (layer) {map.removeLayer(layer);});
    – GeoGyro
    Commented Feb 8, 2018 at 11:09

1 Answer 1

3

If anyone comes across the same issue as me, here's a working solution

//Note: these variables are declared outside of the functions so that I may access them in other functions
//There are alternative methods but this works just as good
var latlngs = []; //array of latlng coordinates used for creating markers for the map
var p; //Variable that's temporary for the layer properties value
var line; //Polyline variable
var markers; //Marker cluster variable
var myMovingMarker; //Moving marker variable
var isMap; //Bool check to see if map has been loaded or not (for selecting new files)
var map; //Map variable 
var tiles; //Tile layer variable

    //Loading the map
    //---------------------------------------------------------------- 
    function loadMap(){
        L.mapbox.accessToken = 'pk.eyJ1IjoiaXNlMTg0NCIsImEiOiJjamNqdTJlcWsxMXJkMnFuc2todm1kd3IyIn0.3sT6Sgr_MXryUFIG7Co2OQ'; //this token is used to load map styles
        // Create a map in the div #map
        map = L.mapbox.map('map');
        //Using my own mapbox style
        tiles = L.mapbox.styleLayer('mapbox://styles/ise1844/cjd3u4m6e4ola2rl04t1cegm4').addTo(map); //my own designed style of map

        //Set display to load map on Western Australia
        map.setView([-34.0153, 93.1673], 4);
        isMap = true; //map is loaded
    }

    //Initialising function for leaflet/mapbox
    //Note: for some reason this is necessary
    function eachLayer(layer) {
        // map.removeLayer(layer);
    }
    //----------------------------------------------------------------
    // 

//Main function for opening the map based on selected file
function openFile(afile){
    //Check if map is loaded, if false then load else remove everything and reload it
    if(isMap != true){
        loadMap();
    }else{
        //For each layer on the map remove everything and clear variables
        map.eachLayer(function(layer){
            map.remove();
            map.removeLayer(layer);
            map.removeLayer(line);
            latlngs = [];
            PointManager.deletePoints(); //clear the pointManager array of points
            isMap = false;
            loadMap(); //reload the map function
        });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.