GrandeurH
GrandeurH

Reputation: 147

How to plot multiple points on mapbox using a for each statement?

I have a 2D array of longitudes and latitudes and I want to be able to map each of these points on MapBox.

My problem is that the example given is for two points, so I tried applying a for-each loop to iterate through my 2D array and plot the points. The problem is you need a unique ID to add a layer. I have being following this tutorial located here : https://www.mapbox.com/help/getting-started-directions-api/

This is the code I have so far, any help would be greatly appreciated!

<body>
//create the map
<div id='map'></div>
<div id='instructions'></div>
<script>
mapboxgl.accessToken = 'ACCESS TOKEN KEY';
var map = new mapboxgl.Map({
  container: 'map', // container id
  style: 'mapbox://styles/mapbox/streets-v9', //stylesheet location
  center: [-6.266155,53.350140], // starting position
  zoom: 12 // starting zoom
});


//load the route function
map.on('load', function(){
  getRoute();
});

//get route takes start and end (lat,long)
function getRoute() {
  //create an array
  var arr = [
    [-6.3053, 53.3562],
    [-6.802586, 53.176861],
    [-6.5991, 53.0918],
    [-6.3053, 53.3562]];

  arr.forEach(function(el, index)
  {


    var nodeOnes = [];
    nodeOnes = arr[0];


    console.log("here" + n);
      map.addLayer({
      id: nodeOnes,
      type: 'circle',
      source: {
        type: 'geojson',
        data: { 
          type: 'Feature', 
          geometry: {
            type: 'Point',
            coordinates: nodeOnes
          }
        }
      }
    });
});
}
</script>

Note I do not include my access token

Upvotes: 1

Views: 2752

Answers (1)

MeltedPenguin
MeltedPenguin

Reputation: 797

Instead of adding independent points with their own layer, you could add a FeatureCollection with all your points:

const allPoints = arr.map(point => ({
    type: 'Feature',
    geometry: {
        type: 'Point',
        coordinates: point
    }
}));

map.addLayer({
    id: 'path',
    type: 'circle',
    source: {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: allPoints
        }
    }
});

Upvotes: 3

Related Questions