why am I encountering difficulty accessing object elements following the addition of values to a 2D array?

Extracting Json Data through an Ajax request:

{
    "VehicleID": 1,
    "Tracks": [{
        "TrackID": 1,
        "trackPoints": [{
            "lat": 36.25514030456543,
            "lng": 33.501180542295344
        }, {
            "lat": 36.255140304562,
            "lng": 33.5011805422952
        }, {
            "lat": 36.255140304561,
            "lng": 33.5011805422951
        }]
    }, {
        "TrackID": 1,
        "trackPoints": [{
            "lat": 31.25514030456543,
            "lng": 31.501180542295344
        }, {
            "lat": 31.255140304562,
            "lng": 31.5011805422952
        }, {
            "lat": 31.255140304561,
            "lng": 31.5011805422951
        }]
    }]
}

Implementation using Google Maps with two nested loops to iterate over tracks and track points, additionally logging output to the console:

for (var i = 0; i < numtracks; i++) {
     var numPoints = result.Tracks[i].trackPoints.length;
     arr[i] = new Array(numPoints); //creating 2d array for points
     console.log("*********Array number " + i + " Got created" + "and its length is " + arr[i].length + "   *******************");
     console.log("Length of track #" + i + " Points => " + numPoints);
     console.log("array length for Points track #" + i + " => " + arr[i].length);

Secondary loop for accessing individual points:

for (var j = 0; j < result.Tracks[i].trackPoints.length; j++) {
    var x = result.Tracks[i].trackPoints[j].lat;
    var y = result.Tracks[i].trackPoints[j].lng;
    console.log("x= " + x + " for #" + j + "  Point");
    console.log("y= " + y + "  for #" + j + "  Point");

Data transmission to Google Maps API:

var p = new google.maps.LatLng(x, y);
console.log("p before pushing latitude: " + p.lat());
console.log("p before pushing longitude: " + p.lng());

Upon storing data in arr[i]:

arr[i].push(p);
//when accessing arr[i][j].lat();is not recognizing it
console.log("track #" + i + " , point #" + j + " pushed into array x= " + arr[i][j].lat() + " ,y=" + arr[i][j]);

The following logs appear in the console:

array length for tracks => 2 trackss:96
Tracks length : 2 trackss:97
*********Array number 0 Got created and its length is 3   ******************* trackss:110
Length of track #0 Points => 3 trackss:111
array length for Points track #0 => 3 trackss:112
x= 36.25514030456543 for #0  Point trackss:116
y= 33.501180542295344  for #0  Point trackss:117
p before pushing latitude for the 36.25514030456543 trackss:119
p before pushing longitude for the 33.50118054229529 trackss:120
Uncaught TypeError: Cannot read property 'lat' of undefined 

Answer №1

Start by initializing the array arr in this way:

arr[i] = [];

Next, add the object p to the array like so:

arr[i][j] = p;

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

Retrieve information from an express server using the fetch API

I am attempting to use the alert function to display a variable string in Express's .get() method and then send it using res. I want the alert to show "I am working fetch". This is my server.js var express = require('express'); var app = e ...

Unable to view HTML without an internet connection

I have encountered an issue where my files work fine when uploaded to an online server, but do not work when accessed locally offline. An error message about a cross-origin issue appears. How can I solve this problem? Error message: Security Error: Conte ...

Adding a Nested Object to a JSON Data Structure

Recently, I had to modify the field type of a column, altering the data layout to a multiple choice field type. The original JSON fetched looked like this: d: { "results": [ { "MajorTasks": null, "DeliverablesSub ...

Contrast the string ID with BSON::ObjectId

I am trying to compare an array containing BSON::ObjectId types with some IDs represented as strings. if my_array_of_BSON_ObjectIds.include?(@my_id_as_a_string) # delete the item from the array else # add the item to the array as a BSON::ObjectId e ...

Assign the twig variable to a JSON file for inclusion

I've been using twig templates to store all my content in a JSON file like this: JSON Data: {% set contentElements = { "json structure": {....} "json structure": {....} %} As time has passed, the JSON files have grown larger and larger. ...

Select a single option from the group to include in the array

I'm currently developing a new soccer betting application. My goal is to allow users to choose the result of a match - whether it's a win, loss, or draw - and then save that selection in a list of chosen bets. https://i.stack.imgur.com/hO3uV.png ...

Converting a one-dimensional JSON array into objects in C#

Given a JSON Array structure with multiple single-dimensional arrays: { "F" : [ "FG3D2", "FG492", "FG4Q2", "FG562", "FG5Y2", "FG6C2" ], "M" : [ "MG3D2", "MG492", "MG4Q2", "MG562", "MG5Y2", "MG6C2" ], "N" : [ "NG3D2", "NG492", "NG4Q2", "NG562", ...

Display the data from the database in a label based on the selection made in the combo box

In an attempt to pass values into a label based on the selected option from a combobox, let's say if I choose A, the label should display 1 and if I select B, it should display 2. Here is my code: kota.php: $conn = mysql_connect('localhost&apo ...

Tips for creating a sequence pattern in JavaScript or jQuery resembling 12345-1234567-8

I am looking to adjust this code so that a hyphen "-" is automatically inserted after every 5 characters, and then again after every 7 characters. Currently, the code only inserts a hyphen after every 5 characters. <html> <head> <scri ...

How to Access ViewBag Value from Asp.Net in AngularJs Controller

Just getting started with AngularJs and encountering an issue with passing a value from a .Net MVC View to an AngularJs Controller. Here's the code snippet in question: AngularJs controller snippet: app.controller("RatingApiController", function ($s ...

Instant disconnection from OBS WebSocket detected

I'm currently working on developing an application to manage OBS, but I encountered an issue while trying to establish a connection with Node. Despite having the correct port and password set up, my connection gets terminated immediately after running ...

An unexpected punctuation token «(» was encountered instead of the expected punctuation when generating a chunk using UglifyJS

I encountered an error while attempting to perform a production build using webpack version 2.2.1: > cross-env NODE_ENV=production webpack --config internals/webpack/webpack.prod.babel.js --color -p --progress Hash: 7bb2cdb98aab2f36f7e1 ...

Encountering unexpected issues with Waypoints.js in Angular views

I have implemented a CSS animation for elements in my views using waypoints.js when they reach the top of the window (at 70% offset). Here is the directive I created: angular.module("myApp") .directive("clWaypoints",function(){ return{ ...

Why are JavaScript errors constantly popping up when I use Django Pipeline?

After configuring Django Pipeline (version 1.3.15) for a specific group of JS files, I ensured they were in the correct order based on their appearance on my page. The collectstatic process went smoothly and when viewing the source, it looked like all th ...

Running into difficulties while attempting to sort through an object utilizing an array

My task is to filter a collection of objects based on an array of Fids. I have an object, $target = $('#tableA tr[data-id="' + elm.id + '"]'); // Collection of tr And I also have an array, var fids = $("#tableB tr .New.selected").pa ...

Guide to reducing the file size of your JavaScript code in Visual Studio Code

Does anyone have any recommendations for a Visual Studio Code plugin that can automatically minify JS files upon saving? I'm looking for a way to streamline the minification process. ...

Error: The 'TypeIt' identifier was not expected. The import call requires only one argument

I'm embarking on my first web development journey, and I've decided to utilize the type it library. However, I seem to be encountering an error whenever I try to import it into my script file. Below is a snippet of my code: Index.html file: < ...

Troubleshooting compatibility issues with Node.js modules on Windows: a comprehensive guide

When I use nodejs to write a command line tool, I encounter an error on Windows. However, there seems to be no problem when running it on Linux and Mac OSX systems. You can find the package at https://www.npmjs.com/package/idoc To globally install, use t ...

Removing a CSS class using JQuery

Within my website layout, I have a div that is dynamically included using PHP. This div is inserted in two different locations, each inside its own parent div. <div id="parent_div"> <div id="contact_details_div" class="contact_details_div sam ...

Best return type for a webservice triggered using jQuery but not requiring any data to be returned

I am currently working on a web service that utilizes several methods. These methods do not have significant impact on the client side as I call them using jQuery/ajax. My main concern is regarding the recommended return type. Typically, I would return JS ...