MapBox clear all current markers

陌路散爱 提交于 2019-12-05 05:08:30

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();

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();
    }
}

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();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!