How to use JavaScript to loop through and parse JSON data from Google Maps API

Hey there, I'm a beginner in javascript and I need some help. I am trying to figure out the best way to access a json object called "js" so that I can display different content for each marker on a map. Right now, all my markers are showing the same key value, which happens to be the last one in the list.


js = JSON.parse(jss);

var infowindow;
infowindow = new google.maps.InfoWindow({
  content: js.length + ' ' + iter //String(jss.length)
});
var iter = 0;

for (var key in js){

  mark = new google.maps.Marker({
    position: new google.maps.LatLng(key*0.5,key*0.5),
    map: map,
    title: 'Uluru (Ayers Rock)'
  });

  google.maps.event.addListener(mark, 'click', function(){
    infowindow.setContent(key.toString());
    infowindow.open(map,this);
  });
}

Answer №1

Consider using a for loop rather than "for in" for better control,

for (var x=0; x<data.length; x++) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(data[x]*0.5, data[x]*0.5),
        map: map,
        title: 'Uluru (Ayers Rock)'
    });
}

Answer №2

Make sure to keep a reference of the key in order to pass it into the onclick function for each iteration of the loop. Here's an example:

var data = JSON.parse(jsonData);

var infoWindow;
infoWindow = new google.maps.InfoWindow({
  content: jsonData.length + ' items' //String(jsonData.length)
});
var index = 0;

for (var key in jsonData){

  var marker = new google.maps.Marker({
      position: new google.maps.LatLng(key*0.5, key*0.5),
      map: map,
      title: 'Location'
  });
  var keyStr = key.toString();
  google.maps.event.addListener(marker, 'click', function(){
      infoWindow.setContent(keyStr);
      infoWindow.open(map,this);
  });
}

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

Instantly refreshing the Angular DOM following data modifications and retrieval from the database

I am currently working on a Single Page Application that uses Angular 8 for the frontend and Laravel for the backend. This application is a CRUD (Create, Read, Update, Delete) system. The delete functionality is working as expected, deleting users with spe ...

Selenium was unable to scroll a sidebar or container

I'm just starting out with selenium and python. I'm trying to scrape the content from a website that has a sidebar (container), and I need to copy its content multiple times while scrolling until I reach the end of the container. However, I&apos ...

When combining Puppeteer with Electron, an error stating "Browser revision not found" may occur. However, this issue does not arise when running with Node

My attempts to make Puppeteer work in Electron have been with various versions of Puppeteer (v5.4.0, v5.4.1, and v5.5.0), on Windows 10/MacOS, and with different Node versions (v12, v14.0.1, v15.0.3). Trying a simple puppeteer.launch() in the main process ...

Using JavaScript to assign one object to another object

I am facing an issue where I am trying to assign the local variable UgcItems to uploadedItems, but when I attempt to return the value, it shows as undefined. If I place the console.log inside the .getJSON function, then I get the expected value. However, t ...

Interactive html5 canvas game with swiping mechanism

Currently, I am in the research phase for a new HTML5 canvas game that I want to create as a personal project to enhance my skills. Surprisingly, I have not been able to find any valuable articles or tutorials online about creating swipe-based games. The ...

A tutorial on filtering a list to only send a specific attribute in a Node.js response

Apologies in advance, I know this may be a simple question/issue but I've been struggling with it for some time. I have an API that is built using ExpressJs and Sequelize. I have successfully retrieved the data, but I am facing an issue when trying t ...

"Including Span icons, glyphs, or graphs within a table cell in AngularJS based on a specified condition or numerical

I'm attempting to incorporate span icons/glyph-icons using Angular within a td before displaying the country. I've utilized the code below to achieve this, but I'm looking for a more dynamic and elegant solution. Your assistance is greatly a ...

Utilizing HTML documents instead of images in Owl Carousel 2

I am currently utilizing owl carousel 2 to construct a basic sliding carousel. However, I am only using images at the moment and would like to incorporate HTML files instead. These HTML files contain multiple divs where images can be inserted, and instead ...

Retrieve information from a JSON file containing multiple JSON objects for viewing purposes

Looking for a solution to access and display specific elements from a JSON object containing multiple JSON objects. The elements needed are: 1) CampaignName 2) Start date 3) End date An attempt has been made with code that resulted in an error displayed ...

What could be causing TypeScript to throw errors when attempting to utilize refs in React?

Currently, I am utilizing the ref to implement animations on scroll. const foo = () => { if (!ref.current) return; const rect = ref.current.getBoundingClientRect(); setAnimClass( rect.top >= 0 && rect.bottom <= window.i ...

Ensuring the absence of values in deconstructed variables within an object

In my quest to efficiently destructure the end_time property from the this.props.auction object, I encountered the code snippet below. const {auction: {auction: {end_time}}} = this.props; The problem with this code is that the constant will be undefined ...

Please anticipate a positive response from the API call

I've been utilizing the Yahoo Api and have included a random sleep method along with hard sleeps. However, I'm still stumped on how to handle cases where I don't receive a response on the first attempt. For instance, the code below fails fo ...

The saving function of the Jquery camera is not working properly and does not store the

I seem to be having an issue when using the jquery camera in "save" mode. Despite trying to call the url in "webcam.save" manually, it doesn't seem to have any effect. It appears that the jquery camera plugin may not be functioning as intended. Any su ...

Populating options in <select> for Internet Explorer version 5

Let me address the first question here. The reason why I am using IE5 is because I am working on a Windows CE device which limits me to this browser. My application involves a webpage with various elements. In my HTML code, I have two text fields and a se ...

How to incorporate a new attribute into a JSON object in node.js

In my quest to enhance a JSON file, I aim to add new fields that are distinct from the existing ones. The structure of the JSON is as follows: objJson={ istructor_id:"12345", student_id:"333", date: "2022-10-5" } I have tw ...

Is there a possibility of encountering an endless update loop within a component's render function?

Hello! I am a beginner in Vue.js and I have encountered an issue with my function. Instead of increasing my variable to 1 as expected, it is increasing it to a random number every time. The console is displaying the following error message: "You may hav ...

Troubleshooting: Why Won't My Basic JQuery POST Request Work?

Can someone help me figure out how to use JQuery to send a POST request and display the data in a PHP file? Here is the HTML file: <html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> ...

What is the Reason for Wrapping Masterpage Javascript File References in a PlaceHolder Control?

While examining the demo project for xVal, a validation framework designed for ASP.NET MVC, I observed that the Masterpage javascript references were enclosed in a PlaceHolder control: <asp:PlaceHolder runat="server"> <script type="text/javas ...

Error in Mongoose validation: "Please provide a value for the 'first' field and the 'last' field."

Another user has previously posted a similar question, but I'm still struggling with my MongoDB website. I am working on a project to store names using mongoose. Here is the code for my routes and models: const router = require("express").Router(); c ...

Modifying the state when an array within another array changes using react hooks

I am faced with a challenge involving an array of objects nested within arrays of objects. My goal is to update a specific object value in the inner array. For example: const [datas, setDatas] = useState([ { id: 1, name: 'john' ...