Home > Net >  Add multiple marker on Mapbox
Add multiple marker on Mapbox

Time:03-26

referring to a codepen demo at https://codepen.io/Maximusssssu/pen/zYpZYZX?editors=1111. As you can see when you click on map, it will place a marker, may I know how to add multiple markers so that the previous marker that I have added does not go away? I would prefer the coordinates(latitide,longitude) to be stored in an array. Please show a demo for understanding :)

function add_marker (event) {
  var coordinates = event.lngLat;
  console.log('Lng:', coordinates.lng, 'Lat:', coordinates.lat);
  marker.setLngLat(coordinates).addTo(map);
}

map.on('click', add_marker);

CodePudding user response:

First of all create a array variable which would collect the markers. const c = [];

Afterwards add this function to your code:

function createMarker(){
   for(var i = 0; i < c.length; i  ){
     const marker = new mapboxgl.Marker({})
       .setLngLat([c[i].lng, c[i].lat])
       .addTo(map);
   }
}

In your add_marker function you have to push the coordinates to the array c. And then call this function inside your add_marker function. This function iterate all markers and set it on your map.

**example / NOTE: it will dont run on stackoverflow because i dont include the mapbox cdn **

    // TO MAKE THE MAP APPEAR YOU MUST
    // ADD YOUR ACCESS TOKEN FROM
    // https://account.mapbox.com
    mapboxgl.accessToken = 'pk.eyJ1Ijoicm9ubSIsImEiOiI3MUpLb2o0In0.NaLkJ3qZjdty3REWEZbodA';
    const map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v11',
        center: [12.550343, 55.665957],
        zoom: 8
    });

    // Create a default Marker and add it to the map.
var marker = new mapboxgl.Marker({});
let c = []
function add_marker (event) {
  var coordinates = event.lngLat;
  
  console.log('Lng:', coordinates.lng, 'Lat:', coordinates.lat);
  c.push(coordinates);
  createMarker();
  
}

map.on('click', add_marker);

function createMarker(){
   for(var i = 0; i < c.length; i  ){
     const marker = new mapboxgl.Marker({})
       .setLngLat([c[i].lng, c[i].lat])
       .addTo(map);
   }
}
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
<div id="map"></div>

To remove the marker

First of all change the var marker in your global scope var marker = []; // instead: new mapboxgl.Marker({});

Add this function

function clearing() {
  for (var i = marker.length - 1; i >= 0; i--) {    
    marker[i].remove();
  }  
}

And replace this loop in your createMarker() function

   for(var i = 0; i < c.length; i  ){
     let m = new mapboxgl.Marker({})
       .setLngLat([c[i].lng, c[i].lat])
       .addTo(map);
     marker.push(m);
   }
  • Related