The loop displays only the final value stored in the array

I'm currently facing an issue where I am trying to display a set of values from an array, but it only seems to be showing the last value. How can I ensure that all values are displayed?

When I inspect longLat[itemIndex], I notice that the values should all be in the same array.

Collapsed:

https://i.sstatic.net/iwG8T.png

Expanded:

https://i.sstatic.net/9N0Vi.png

My code snippet-

let longLat = []

for (let index of this.overwatchTargets) {
  let coordsArr = [index["longitude"], index["latitude"], index["userName"], index["dateTimeCaptured"]]
  longLat.push(coordsArr)

  for (let itemIndex in longLat) {
    // Update location coordinates
    this.map.getSource('data-source').setData({
      "type": "FeatureCollection",
      "features": [{
        "type": "Feature",
        "properties": {
          'description': "Dispatcher: " + longLat[itemIndex][2] + "\n" + "Lng/Lat: " + longLat[itemIndex][0] + " / " + longLat[itemIndex][1] + "\n" + "StartTime: " + longLat[itemIndex][3]
        },
        "geometry": {
          "type": "Point",
          "coordinates": longLat[itemIndex] <--- This should display all elements in the array, but it only shows the last one
        }
      }]
    });
  }
}

Answer №1

Instead of repeatedly passing a single-element array, consider passing a single collection of coordinates in one go.

It may be helpful to create a method like

convertIndexToFeature(index) {
  const {longitude, latitude, userName, dateTimeCaptured} = index;
  return {
    "type": "Feature",
    "properties": {
      'description': "Dispatcher: " + userName + "\n" + "\Lng/Lat\:" + longitude + " / " + latitude + "\n" + "\StartTime\: " + dateTimeCaptured
    },
    "geometry": {
      "type": "Point",
      "coordinates": [longitude, latitude, userName, dateTimeCaptured]
    }
  };
}

Then simplify your main body with

this.map.getSource('data-source').setData({
    "type": "FeatureCollection",
    "features": this.overwatchTargets.map(convertIndexToFeature)
});

This will allow you to call setData just once, transforming the entire array of overwatchTargets into an array of features.

Answer №2

Splitting up these two for loops could make a difference

let locationData = []

for (let record of this.overwatchTargets) {
  let coordinates = [record["longitude"], record["latitude"], record["userName"], record["dateTimeCaptured"]]
  locationData.push(coordinates)
}

for (let index in locationData) {
    // Update location information
    this.map.getSource('data-source').setData({
      "type": "FeatureCollection",
      "features": [{
        "type": "Feature",
        "properties": {
          'description': "Dispatcher: " + locationData[index][2] + "\n" + "Lng/Lat: " + locationData[index][0] + " / " + locationData[index][1] + "\n" + "StartTime: " + locationData[index][3]
        },
        "geometry": {
          "type": "Point",
          "coordinates": locationData[index]
        }
      }]
    });
  }

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

Creating a Three-Dimensional Bounding Box in THREE.js

After successfully utilizing the OBB.js in three.js examples to fetch the center, halfSize, and rotation values, the next step is to determine how to calculate the 8 corners of the bounding box based on this information. Additionally, we need to understa ...

Confirming Bootstrap - Implement an onConfirm method for element attributes

I am looking to add a JavaScript function to my confirmation button. I have created the elements off-page and fetched them using ajax, so it is crucial that I can set the function in-properties rather than via $('#id').confirmation() So far, I h ...

How can I determine if the td I clicked on is in the first row or the last row, and how do I find out its row and column

I am working with a table that looks like the one in this link. https://i.sstatic.net/LCoLw.png Is there a way for me to determine if the td (input) I clicked on is in the first row or last row? Additionally, how can I figure out the column index and ro ...

"Discovering the method to showcase content based on page number or when the 'previous' or 'next'

Here is how my Vue component looks like: <template> ... <b-col v-for="item in items" v-bind:key="item.id" cols="2"> ... <strong slot="header" class="text-dark" :title ...

Creating a Unique Window Design with List View Component in Kendo UI

I am trying to create a customized Kendo Window with two Kendo List Views, an Add button, and a Remove button inside. Right now, my main goal is to display a list of data in the List view within the Kendo Window. Below is the JavaScript code I have: ...

Query MongoDB using an OpenWhisk action

Having trouble creating an OpenWhisk action that executes a find query in MongoDB and returns the results? No worries, as I am having difficulty getting it to work correctly. Even though I've connected OpenWhisk with MongoDB properly, I'm still n ...

What is the best way to create an array within an object in JavaScript?

Here is the code snippet I'm working with: var Memory ={ personAbove: "someone", words: wordsMem = [] <<<<<this part is not functioning properly } I need help figuring out how to make it function correctly. Specific ...

When it comes to Django MongoDB Querysets, you may encounter difficulties when attempting to print or iterate

When attempting to run a MongoDB raw query in Django using the following code: queryset= ObjectClass.objects(__raw__={ }) I encounter an error message when trying to print or iterate through the queryset. The error states: "error_message": "cannot conve ...

Saving an image to a variable in React Native by using a URL

Is it possible to save an image from a URL into a variable and then use it in the Image component? In the code snippet provided below, the image is loaded directly, but I would like to create a function that stores the image in a variable for offline use ...

CoffeeScript does not recognize the Angular controller function

I am new to using Angular and CoffeeScript in combination, integrating it into a Rails project. My goal is to create a function within the controller that triggers upon clicking a button in the view. Below is the HTML markup: <div id="labs"> < ...

Can Vue support recurring time slots?

I have configured a reproduction repository: https://github.com/devidwong/recurring-slot Using Vue runtime-only, I am unable to use Vue.extend (which requires template compiler) Vue 3 is quite new to me. I decided to use it for exploration purposes. Not ...

The embedded video from YouTube refuses to appear behind other elements

I am facing an issue with YouTube embedded videos on my website. The problem is that these videos do not follow the z-index rules and are always displayed above all other elements on the page. I have tried: $('iframe','.video_container&apos ...

Decoding a barcode using JavaScript

Currently, I am facing an issue with my barcode gun scanner. It reads barcodes into input fields but returns each digit separately instead of as a whole string. This has been quite bothersome for me. For instance, when I scan the barcode of a bottle of wa ...

What could be causing my JavaScript code to continuously run in a loop?

Below is the code snippet that I am currently working with: JS <script type="text/javascript"> $(function(){ $('#fgotpwfield').hide(); $('#login_submit').click(function() { $('#form_result').fade ...

The route for ` http://localhost/admin/` seems to be experiencing issues, however, it functions correctly when accessed through

Greetings everyone! Currently, I am diligently working on a project using AngularJS. Everything runs smoothly when accessing the project through this route: http://localhost/. However, I encounter an issue with the admin panel link: //localhost/admin/. I ...

Adjusting body styles in a NextJS application using localStorage prior to hydration: A step-by-step guide

If you visit the React website and toggle the theme, your choice will be saved in localStorage. Upon refreshing the page, the theme remains persistent. In my NextJS project, I am attempting to achieve a similar outcome by applying styles to the body eleme ...

Obtain headers from receiving an external JavaScript file

I am trying to find a way to import an external .js file and access the response headers from that request. <script src="external/file.js?onload=callback"> function callback(data) { data.getAllResponseHeaders(); } </script> Unfortunately, ...

Tips for using the redirectTo feature when signing in using Supabase and Nuxt

This is the code snippet I've been using that is functional: const redirectTo = `${window.location.origin}${query.redirectTo}`; const { error } = await client.auth.signInWithOAuth({ provider: "google", options: { redirectT ...

The SOAP request did not return an array with strings as expected, but rather an empty array, when

Encountered a situation where sending a SOAP request with an array of strings through Ajax results in the request being successfully passed to the web service. However, upon deserialization, the array is rendered empty. The ASP.Net WebService features the ...

No Response from Ajax Request

I am working with the following Script; function FetchNews(user_id,api_token){ $.ajax({ type:'GET', url: 'http://192.168.**.**/mysite/public/index.php/api/v1/news/'+user_id, headers: {'X- ...