What is the best approach for looping through this JSON data?

After retrieving the following JSON data from a database using ajax:

{"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]}

What is the best approach for iterating over it to extract latitude and longitude pairs for plotting on a map?

Answer №1

Store the JSON data in a variable and iterate through the route object as shown below:

var jsonData = {"route":[{"latitude":-34.397,"longitude":150.644},{"latitude":-35.308,"longitude":149.124}]}

for(var i=0; i<jsonData.route.length; i++){
  var currentRoute = jsonData.route[i];   
}

Answer №2

Why not give this a shot:

let coordinates = {"path":[{"lat":-27.38851,"long":153.11606},{"lat":-27.47577,"long":153.01693}]};
for(let i= 0,len=coordinates.path.length; i<len; i++){
  let latitude = coordinates.path[i].lat;
  let longitude = coordinates.path[i].long;
  console.log(latitude+' '+longitude);
}

Answer №3

let location = {"route":[{"latitude":-33.8657,"longitude":151.2094},{"latitude":-37.8136,"longitude":144.9631}]};
let index = 0;
let latitude, longitude;
let routeLength = location.route.length; 
for(index,index<routeLength; index++){
  latitude = location.route[index].latitude;
  longitude = location.route[index].longitude;
  console.log(latitude+' '+longitude);
}

Answer №4

Check out this complete implementation to achieve your goal:

JSFiddle example with a map

  To create a marker on the map, use the following function:
    function createMarker(options) {
        var marker = new google.maps.Marker(options);

        return marker;
    }

    Iterate through the data route and create markers for each location:
    for (i = 0; i < data.route.length; i++) {
        createMarker({
            position: new google.maps.LatLng(data.route[i].latitude, data.route[i].longitude),
            map: map
        });

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

If a specific key/value pair in an object meets a certain condition, transfer (or duplicate) the pair to a different object

Looking for a solution to extract specific data from two large files: from_file: [ { "id": 7212486534162308, "rowNumber": 283, "cells": [ { "Column": "SS name", ...

MUI Alert: Encountered an Uncaught TypeError - Unable to access properties of undefined when trying to read 'light' value

After utilizing MUI to create a login form, I am now implementing a feature to notify the user in case of unsuccessful login using a MUI Alert component. import Alert from '@mui/material/Alert'; The code snippet is as follows: <CssVarsProvide ...

retrieve only the following occurrence throughout the entire file

I am looking to target only the first occurrence of an element in the document after a clicked element. Here is my current approach: $('.class').click(function(){ var x = $(this).nextAll('.anotherclass').first(); //do something ...

What is the best way to convert base64 into an image using Node.js?

I'm having trouble with decoding an image sent as base64 through sockets. The file that should contain the image is being written as a base64 string instead of a jpg file. For encoding through socket: function encode_base64(filename) { fs.readFile( ...

The controller and node js request associated are invisible to my HTML page

Here is my HTML code. I have just created a unique controller for a specific part of the code. <div class="mdl-grid" ng-controller="ValueController"> <div class="mdl-card mdl-shadow--4dp mdl-cell--12-col"> <div class ...

Retrieve information from an SQL database using user input in a Classic ASP form without the need to refresh the page

Currently, I am in the process of incorporating a new function into an existing Classic ASP system. This feature involves allowing users to scan a barcode that will automatically populate a text field within a form inside a bootstrap modal. The scanner has ...

Ways to steer clear of using eval for converting strings to decimal values

I currently have the fraction "1/7" and I am looking to convert it into a decimal. While I know I can achieve this using eval("1/7"), I prefer not to use eval as it is considered harmful. Are there any alternative methods to accomplish this? ...

Utilizing handpicked information in Angular: A beginner's guide

Being new to Angular and programming in general, I am currently navigating through the intricacies of Angular and could use some guidance on utilizing selected data. For instance, I would like to use a personnel number view image here and send it to the b ...

"Experimenting with KinectJS: Adding Rotation to a Pair of Images

Looking for a solution to rotate both the upper arm and forearm images simultaneously? The upper arm rotates around a specific point, and the forearm also rotates around this same point. How can I make sure that the forearm rotates when the upper arm does ...

Inconsistencies with AJAX performance

Hey there, I'm a newbie and absolutely loving this site! Currently diving into the world of JavaScript and have been through numerous tutorials. However, I seem to be struggling with getting Ajax to work. Recently stumbled upon this code snippet on ...

Encountered a parsing error when attempting to integrate SCSS with webpack and babel setup

I am facing an issue while trying to integrate SCSS into my webpack and babel setup. When running npm run build, I encounter an error that I'm unfamiliar with. As a beginner in using webpack and babel, I'm unsure about the necessary changes requ ...

On initial loading, Materialize JS seems to experience technical difficulties

Struggling to develop a Vue.js SPA chat application, encountering issues with Materialize CSS and JS. The JS doesn't function properly on initial load and requires a page reload to work. No errors are appearing in the console, making it challenging to ...

What could be the reason for the malfunction of $http.get method?

Having trouble accessing a JSON file and using alert to debug the issue, but it doesn't seem to be working. Any insights on why this might be happening would be greatly appreciated. Thanks! app.controller("MainController", function($scope, $http) { ...

Creating a toggle label using just CSS: a step-by-step guide

Recently, I was trying to create a toggle label using HTML, CSS, and JavaScript. Here is the code snippet that I experimented with: function genre_itemclick(item){ if(item.classList.contains('light_blue_border_button')) { ...

Is there a tool available on the command line to detect simple Javascript syntax mistakes?

Is there a command-line tool in Linux that can identify basic syntax errors and compile time errors in JavaScript files intended for web browsers? Usually, I write my JavaScript code alongside server-side languages like Ruby or Perl. It would be beneficia ...

Fuzzy picture utilizing <canvas>

Working on translating a webgame from Flash to HTML5 with pixel art sprites, I've noticed that the canvas appears blurry compared to Flash where pixels are more defined. <!DOCTYPE html> <html> <body> <canvas id="c" style="bor ...

When using JavaScript's Date() function, it may sometimes return an

I am currently developing a website that calculates the time elapsed since a specific date. However, when I input the parameters provided by the user and call new Date(), it displays "Invalid Date". This is the code snippet I have been using: http://jsfid ...

Secure your password with Vue JS encryption techniques

I am looking for a way to safely encrypt passwords on my Vue JS web application. While I already have a hash encrypter set up on the API, I am running into an issue where the password is displayed as plain text during the signin or signup call. Any recom ...

The input field does not accept any values even after setting it to be editable

Hey there! I have a specific requirement where I need to edit certain fields by clicking on an edit link. Initially, these fields will be disabled and in a readonly state. Once I click on the edit link, the field should become blank and editable. The issu ...

Error messages in login form using AJAX in Rails

My issue seems to be quite complicated, but let's simplify it. I am working with devise and I need to display error messages below the form on my login page. Currently, when a user enters the wrong password, I see an error POST 401 (Unauthorized) in t ...