Guide to displaying numerous points on mapbox by utilizing a for each loop statement

I have a 2D array containing longitudes and latitudes that I need to map using MapBox.

The example I found only demonstrates plotting two points, so I attempted to use a for-each loop to iterate through my 2D array and plot all the points. However, I encountered an issue with needing a unique ID to add a layer. I have been following a tutorial on this topic which can be found here:

Below is the current code I have, any assistance 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>

Please note that I have not included my access token for security reasons.

Answer №1

One way to streamline your point additions is by consolidating them into a FeatureCollection:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to create the complete PDF file using html-pdf in a NodeJS environment

When trying to create a PDF from an HTML template, I am encountering some difficulties. While it works with static entries, I want to generate the PDF for multiple items that can vary each time. I feel like I might be overlooking something, so any suggesti ...

Executing the slideToggle() function in JQuery with javascript

Trying to create a script that expands and collapses when users click on either the text or image. The image is a basic arrow that switches to an arrow pointing upwards when the div is expanded. The issue I'm facing is that the text disappears when t ...

How can I show only the final four digits of an input field using Angular Material and AngularJS?

As a newcomer to Angular Material and Angular JS, I am striving to create an md-input field that displays only the last 4 digits in a masked format, such as "********1234". While my experience is currently limited to using md-input password fields where ...

How can I dynamically assign @ViewChild('anchor_name') to a newly updated anchor element in Angular 2+?

Upon receiving an item through a GET request, I set the item_id upon subscription. In the HTML file, I create a div with an anchor id="{{this.item_id}}". However, I encountered the following error: FeedComponent.html:1 ERROR TypeError: Cannot read propert ...

Julia array pushing woes: struggling to create nested arrays with varying dimensions

In my code, there is a loop structured like this: edge_weights = Int[]; edge_weights_array = [edge_weights for _ in 1:199]; #creating a function to determine column indices function get_columnindices(graph_base_table)::Tuple{Int,Int} ncol(graph_base_t ...

Having trouble locating an external Javascript file in a Node.JS/Express app with Jade template?

In my Node.JS/Express app, I am using the Jade template engine. The issue arises when trying to reference a server-side Javascript file named common_routines. Despite placing the Javascript file in the directory above my views directory and referencing it ...

Is there a way to tally the checked mat-radio-buttons in Angular?

I am seeking a way to determine the number of radio buttons checked in a form so I can save that number and transfer it to a progress bar. <mat-radio-group name="clientID" [(ngModel)]="model.clientID"> <mat-radio-button *ngFor="let n of CONST ...

Automatically switch Twitter Bootstrap tabs without any manual effort

Is there a way to set up the Twitter Bootstrap tabs to cycle through on their own, similar to a carousel? I want each tab to automatically switch to the next one every 10 seconds. Check out this example for reference: If you click on the news stories, yo ...

Calculate the sum in real-time using JavaScript

How can I dynamically compute the sum of subtotals without encountering the following error? document.getElementById("item_subtotal[" + cnt + "]") is null Below is my JavaScript code: function calculateTotalAll(numitems) { var cnt = 1; var tot ...

Transfer information from an HTML document to a Vue application that has been registered

I have a Vue application set up in the following manner: import { createApp } from 'vue'; import RecommendedJobsWidget from './RecommendedJobsWidget.vue' createApp(RecommendedJobsWidget).mount("#recommendedJobsWidgetInstance" ...

Transform the object into an array of bytes

I need to convert a registry value, stored as REG_BINARY, from object to byte[]. I attempted to use BinaryFormatter with MemoryStream, but it added unnecessary overhead information. I noticed this when converting the byte array to a string using Convert. ...

Unexpected Timed Out error from Socket.IO adapter when MongoDB connection is lost

I have been experimenting with capturing the disconnection event in mongodb. Everything is working smoothly with this setup: simple.js 'use strict'; var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:2701 ...

An unrecoverable error has occurred in the SetForm function: PHPMailer::SetForm() method is not defined

While working on form validation in jQuery with a WAMP server, I encountered two errors: Fatal error: Uncaught Error: Call to undefined method PHPMailer:: SetForm() and Error: Call to undefined method PHPMailer::SetForm(). I have already added PHPMailerAu ...

What strategies can I use to control the DOM within the onScroll event in ReactJS?

I am currently working on implementing an arrow-up button that should be hidden when I am at the top of my page and displayed once I scroll further down. However, I am facing issues with manipulating the DOM inside my handleScroll function to achieve this. ...

Exploring the use of leaflets within LitElement

I have been working on a project involving LitElement components and I am looking to incorporate Leaflet into it. However, I am encountering difficulties with displaying the map properly. After installing Leaflet through npm in my project, I created a clas ...

.class selector malfunctioning

I'm currently developing a card game system where players can select a card by clicking on it and then choose where to place it. However, I've encountered an issue where nothing happens when the player clicks on the target place. Here is the li ...

Code snippets to reduce excess white space on a website using HTML and CSS

On my website, there are multiple tabs, each containing content from an HTML file. When a user clicks on Tab1, boxes with images are displayed. The layout can be seen in the following Code Demo: Code Demo here There seems to be extra space before and afte ...

Eliminating an element from an object containing nested arrays

Greetings, I am currently working with an object structured like the following: var obj= { _id: string; name: string; loc: [{ locname: string; locId: string; locadd: [{ st: string; zip: str ...

Tips on causing JavaScript execution to halt until an element has finished rendering

test.view.js timeDBox = new sap.ui.commons.DropdownBox({layoutData: new sap.ui.layout.GridData({linebreak: true}), change: function(oEvent){ oController.getKeyEqChart(); }, }), new sap ...

Customizing Material UI: Grouping Tab components within a div container

How can I wrap the children of a Material UI Tabs component in divs? <Tabs value={value} indicatorColor="primary" textColor="primary" onChange={handleChange} > <div> <Tab label="x" /> ...