Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add multiple marker on Mapbox

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading