Is the fetch function returning data in a format that is not ideal?

I am having trouble understanding the behavior of my code. I am attempting to load data using the code provided below. However, when the 3 commented-out lines are uncommented, the console.log displays an empty array [], and the remaining code fails to function properly even though I am not currently utilizing the fetched data.

Interestingly, if I comment out the problematic 3 lines and the console.log shows (5) [i, i, i, i, i], the rest of the code executes as expected - plotting markers on a leaflet map. The consistency in numbering between the two sets of data (0-4) is puzzling, given that they appear to be formatted differently.

Any assistance would be greatly appreciated.

var groupMarkers = [];

async function getData() {
    const response = await fetch('../../Export2.log');    //These are the lines causing problems
    var data = await response.text();                     //These are the lines causing problems
    var formatedData = JSON.parse('[' + data.trim().replace(/\n/g, ',') + ']')   //These are the lines causing problems


    for (var i = 0; i < 5; i++){
        marker = L.marker([51.5, -0.09]).bindPopup("I am a green leaf.");
        groupMarkers.push(marker);
    }
}
getData();
setInterval(getData, 5000);
L.layerGroup(groupMarkers).addTo(map);
console.log(groupMarkers);

If you'd like to test the entire page, here is the HTML snippet:

<!DOCTYPE html>
<html>
<head>
    
    <title>Map Data Test</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />

    <link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="305c5551565c554470011e061e00">[email protected]</a>/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="69050c080f050c1d2958475f4759">[email protected]</a>/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>


    <style>
        html, body {
            height: 100%;
            margin: 0;
        }
        #map {
            width: 100%;
            height: 100%;
        }
    </style>

  </head>
  <body>
    <div id='map'></div>

<script type="text/javascript">

// Start Map
var map = L.map('map').setView([51.5, -0.09], 7);

L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
    maxZoom: 18,
    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
        '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
        'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    id: 'mapbox/light-v9',
    tileSize: 512,
    zoomOffset: -1
}).addTo(map);


var groupMarkers = [];

async function getData() {
    const response = await fetch('../../Export2.log');
    var data = await response.text();
    var formatedData = JSON.parse('[' + data.trim().replace(/\n/g, ',') + ']')


    for (var i = 0; i < 5; i++){
        marker = L.marker([51.5, -0.09]).bindPopup("I am a green leaf.");
        groupMarkers.push(marker);
    }
}
getData();
setInterval(getData, 5000);
L.layerGroup(groupMarkers).addTo(map);
console.log(groupMarkers);
</script>
  </body>
</html>

Answer №1

Implement the use of a then along with fetch:

  var markers = [];
  var featureGroup = L.featureGroup().addTo(map);
  async function fetchData() {
    const response = fetch("Export.log")
    .then(response => response.text()) // or `response.json()` to receive a JSON object
    .then(data => {
      console.log(data);
      featureGroup.clearLayers();
      var jsonData = JSON.parse("[" + data.trim().replace(/\n/g, ",") + "]");
      console.log(jsonData);
      jsonData.forEach((coordinates)=>{
        console.log(coordinates)
        var marker = L.marker([coordinates.Lat, coordinates.Long]).bindPopup("I am a green leaf.");
        markers.push(marker);
        featureGroup.addLayer(marker);
      });
      map.fitBounds(featureGroup.getBounds())
    });
  }
  fetchData();
  setInterval(fetchData, 5000);

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

What is the best way to align two bootstrap buttons next to each other?

Is there a way to align buttons on a modal side by side? One button is a download link and the other a mirror link. I attempted to use a custom class with CSS property "display: inline-block;" but it did not work as expected. Any suggestions on how to achi ...

Having trouble receiving accurate intellisense suggestions for MongoDB operations

Implementing communication between a node application and MongoDB without using Mongoose led to the installation of typing for both Node and MongoDB. This resulted in the creation of a typings folder with a reference to index.d.ts in the server.ts file. In ...

I can't seem to figure out what's causing this error to pop up in my coding setup (Tailwind + Next.js). It

I've been struggling with this problem for a week now and despite my efforts, I haven't been able to find a solution yet. However, I have made some progress in narrowing down the issue. The problem arises when I try to execute the yarn build comm ...

Rotating a multidimensional array in R

Working with a multi-dimensional array is quite interesting: > dim(Sales) [1] 35 71 5 It allows for operations such as comparing sales year over year: Sales_Increase_Y2_to_Y1 = Sales[,,2]-Sales[,,1] Now, the goal is to shift one dimension to calcul ...

How can I retrieve objects using the JSON function?

I need to design a function that returns objects like the following: function customFunction(){ new somewhere.api({ var fullAddress = ''; (process address using API) (return JSON data) })open(); } <input type= ...

Navigating the same origin policy in Mozilla: A step-by-step guide

I have implemented YUI autocomplete in my project by creating a web service that provides suggestions. Everything works fine when both the application and the web service are deployed on the same machine. However, when I deploy the web service on a differe ...

Triggering on multiple clicks - MULTIPLE CLICKS

I'm currently in the process of developing a website and I have a specific requirement where I need an image to change on click to another image, and then to a third image on the second click, and so forth. I've managed to create a JavaScript fu ...

In Express JS, the REST API encounters an issue where req.body is not defined

I am currently working on building a REST API with Express JS. When I use console.log(req.body), it is returning undefined as the output. Below is the code snippet from my routes.js file: const express = require('express'); const router = expres ...

Performing an Ajax request to the server and then sending the retrieved data back to Charts.js

After extensively researching ajax, php, and related topics, I'm facing a challenge. I want to take an array retrieved from my database and integrate it into a chart.js script. The data retrieval seems fine as per Firebug inspection, but the issue ari ...

Caution: It is important for each child in a list to possess a distinct "key" prop. This is a crucial step in

Just started learning react and encountered this warning message: Warning: Each child in a list should have a unique "key" prop. Check the render method of `TravelerStoriesPage`. Here's the code snippet for TravelerStoriesPage: const Trave ...

Fill the table with information from a JSON file by selecting options from drop-down menus

I am currently working on a web application project that involves bus timetables. My goal is to display the timetable data in a table using dropdown menus populated with JSON information. While I believe I have tackled the JSON aspect correctly, I am facin ...

How to Trigger a Google Apps Script Function from an HTML Page

I lead a sports team and created a website for it. I'm interested in adding a button to an admin page that allows me to send a quick email to all team members at once. The message would typically read: "Important update - please check the website for ...

I am unable to showcase the image at this time

Hey there, I'm having an issue with displaying an image stored inside the NextJS API folder. The alt attribute is showing up fine, but the actual image isn't displaying. When I console.log the image data, everything seems to be in place. Can anyo ...

Steer clear of utilizing Number() when working with scientific notation

I am attempting to perform the following task Number("0.00000000000122") yields 1.22e-12 However, my goal is to convert that number from a String to a Number. console.log(Number("0.00000000000122")) ...

Utilizing URL Parameters and Query Strings in React Router: A Comprehensive Guide

Can someone help me retrieve the foo parameter value from http://localhost:3000/params?foo=123? I keep encountering an error message: Error: Params(...): No render output was returned. This typically indicates a missing return statement or returning null ...

Calculate the combined sum of values within dynamic inputs that share a common class, and automatically update the sum whenever input values are altered or new rows are added or removed dynamically

$("#add-btn").click(function() { $("#dynamic").append('<tr>' + '<td class="td">' + '<input type="number" name="Debit" class="form-control Debit"/>' + '</td>' + '<td c ...

Unclear about the data retrieved from a Google Docs Spreadsheet using PHP and fopen()?

Below is the code snippet I'm utilizing to extract data from a public Google Docs spreadsheet that has been exported as a CSV file. <?php // Google Docs spreadsheet link $url='https://docs.google.com/spreadsheet/pub?key=xxxx&output=csv&ap ...

The reason for my inability to include a fresh method in String.prototype using typescript

I attempted to extend the String.prototype with a new method, but I encountered an issue. interface String { newMethod(): void } String.prototype.newMethod = function() {} Although there were no errors in the typescriptlang.org playground, I received ...

Explore the array by locating elements based on the initial two letters of each word in the array

In the given array, I am looking to find the first letters in multiple words within the same matrix. It should search through each word and return in an array if found. For example: const data= [ "the lions of teranga", "tiger ...

Using an array in the WHERE clause with PDO

My array called family is structured as follows - Array ( [0] => 2510-24 [1] => 2510-48 [2] => 2510G [3] => 2520 [4] => 2520G [5] => 2530ya [6] => 2530ya3 [7] => 2530yb [8] => 2610 [9] => 2615 [10] => 2620 [11] => 2626 ...