MapBox clear all current markers

后端 未结 3 594
忘掉有多难
忘掉有多难 2020-12-18 22:45

I\'ve created a MapBox instance with:

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


        
相关标签:
3条回答
  • 2020-12-18 23:08

    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();
    
    0 讨论(0)
  • 2020-12-18 23:18

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

    0 讨论(0)
  • 2020-12-18 23:26

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题