简体   繁体   中英

How to remove the mapbox marker

I have a function called draw() . I pass in the array value inside draw() to plot my desired marker on the map and its working well!!

function  draw(j){
      
    //for (let j =0; j< countvalue[0]; j++){
      array[j].features.forEach(function (marker) {
        // create a HTML element for each feature
        var el = document.createElement('div');
        el.className = 'marker';

var el = document.createElement('div');
el.className = 'marker';


el.style.backgroundImage =
'url(https:gin/images/pin.png)';
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';
el.style.backgroundSize = '100%';
        // make a marker for each feature and add it to the map
    
        new mapboxgl.Marker(el)
          .setLngLat(marker.geometry.coordinates)
          .setPopup(
            new mapboxgl.Popup({ offset: 25 }) // add popups
              .setHTML('</h3><p>' + marker.properties.description + '</p>' )
          )
          .addTo(map);
});

}

My Question:

How will i call the draw() function to remove the marker? Pardon me if this is not possible. Thanks a lot for your time

Create a list of markers that are being added to the map and pass a value to clear all existing markers when required.

let markersList = []

function  draw(j, clearAll){
      
     if(clearAll){
       if(markersList){
         for (var i = markersList.length - 1; i >= 0; i--) {
           markersList[i].remove();
        }
      }
     }
    //for (let j =0; j< countvalue[0]; j++){
      array[j].features.forEach(function (marker) {
        // create a HTML element for each feature
        var el = document.createElement('div');
        el.className = 'marker';

var el = document.createElement('div');
el.className = 'marker';


el.style.backgroundImage =
'url(https:gin/images/pin.png)';
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';
el.style.backgroundSize = '100%';
        // make a marker for each feature and add it to the map
    
        const newMarker = new mapboxgl.Marker(el)
          .setLngLat(marker.geometry.coordinates)
          .setPopup(
            new mapboxgl.Popup({ offset: 25 }) // add popups
              .setHTML('</h3><p>' + marker.properties.description + '</p>' )
          )
          .addTo(map);

        markersList.push(newMarker);
});

}

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