Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapBox clear all current markers

I've created a MapBox instance with:

var map = new mapboxgl.Map({
    container : 'map',
    style : 'mapbox://styles/mapbox/streets-v9'
});

I need to clear all markers, and have tried things like map.remove(marker) on each one, and a few other things, but nothing seems to work.

Is there a simple function call to just clear all markers from the map?

EDIT: Different from How to remove all layers and features from map? because I get "eachLayer is not a recognised function" (or similar) in console.

like image 505
HomerPlata Avatar asked Sep 11 '17 12:09

HomerPlata


3 Answers

You saw this? https://www.mapbox.com/mapbox-gl-js/api/#marker#remove

Instead of map.remove maybe try marker.remove:

var marker = new mapboxgl.Marker().addTo(map);
marker.remove();
like image 125
Andi-lo Avatar answered Nov 18 '22 13:11

Andi-lo


If you added multiple markers, and you want to clear all them on your map, you have to loop overs all markers, and delete them one by one, you will have something like this :

if (currentMarkers!==null) {
    for (var i = currentMarkers.length - 1; i >= 0; i--) {
      currentMarkers[i].remove();
    }
}

Consider thar var currentMarkers contains all markers, you can do this with sometning like :

oneMarker= new mapboxgl.Marker(currentMarkerDiv)
    .setLngLat(marker.geometry.coordinates)
    .addTo(mapboxMap);
    currentMarkers.push(oneMarker);

Where var currentMarkers is a global variable :

var currentMarkers=[];

Full example :

// markers saved here
var currentMarkers=[];

// tmp marker
var oneMarker= new mapboxgl.Marker(currentMarkerDiv)
    .setLngLat(marker.geometry.coordinates)
    .addTo(mapboxMap);

// save tmp marker into currentMarkers
currentMarkers.push(oneMarker);


// remove markers 
if (currentMarkers!==null) {
    for (var i = currentMarkers.length - 1; i >= 0; i--) {
      currentMarkers[i].remove();
    }
}
like image 32
AIT MANSOUR Mohamed Avatar answered Nov 18 '22 15:11

AIT MANSOUR Mohamed


If you added the markers like this (to be able to add styling and custom images as markers), then you can simply remove the class (I did it through Jquery though).

Adding markers that are in a GeoJson:

GeoJson.features.forEach(function(marker) {
var el = document.createElement('div');
el.className = 'marker';
new mapboxgl.Marker(el).setLngLat(marker.geometry.coordinates).addTo(map);
});

Removing markers:

$( ".marker" ).remove();

like image 1
Ralph1983 Avatar answered Nov 18 '22 13:11

Ralph1983