Utilizing the Google Maps API to display dynamic markers in a loop, with changing attributes

I am currently facing an issue with Google markers in the Maps API.

Below is the code snippet from an AJAX success function (where 'map' is a parameter containing this code):

success: function(data) {
   var tmpmap = map;                         // Necessary for adding markers to the map
   ris = JSON.parse(data);                   // Parsing JSON data
   for (var i = 0; i < ris.length - 1; i++) {// Looping through the data
      var id = ris[i].id_sede;               // Retrieving ID from JSON
      var marker = new google.maps.Marker({  // Creating a marker
         map: tmpmap,
         mid: id,                            // Issue arises here
         position: {
         lat: parseFloat(ris[i].latitude),
         lng: parseFloat(ris[i].longitude)
      }
});

The data retrieved by AJAX consists of a standard SQL query containing latitude, longitude, ID, and additional information.

The problem I'm encountering is that each marker created during the loop assumes the value of the current "mid" (map ID).

In short, if I have 4 markers with IDs 1, 2, 3, and 4, by the end of the loop, all markers end up having the ID of 4 instead of 1, 2, 3, and 4 separately.

My main question is: How can I prevent this behavior? Am I creating markers correctly? And why do changes to one marker affect all others?

Answer №1

To ensure that each marker gets its own data, it is necessary to utilize an Immediately Invoked Function Expression (IIFE):

success: function (data) {
  var tmpmap = map; // Storing map reference
  ris = JSON.parse(data); // Converting data to json
  for (var i = 0; i < ris.length - 1; i++) { // For loop
    // IIFE
    (function (entry) {
      // Saving original element as variable entry
      var marker = new google.maps.Marker({ // Creating a marker
        map: tmpmap,
        mid: entry.id_sede, // Retaining the original ID
        position: {
          lat: parseFloat(entry.latitude),
          lng: parseFloat(entry.longitude)
        }
      });
    }) (ris[i]); // Passing original element into IIFEE
  }
});

Without an IIFE, the variable i may reach the condition ris.length - 1 before the first marker obtains its ID. Consequently, the variable id would not hold the ID of the initial marker.

Using an IIFE allows accessing the original entry-element from ris.

I hope this explanation clarifies things for you.

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

Guide to automatically redirecting back to the login page after successfully creating a new account using Redux Saga

Having just started working with redux-saga, I'm encountering an issue where I can't seem to be redirected back to the login page after successfully creating an account. Even though I've implemented the necessary code for redirection, I keep ...

Retrieving an array of data from an API's response

I'm currently working on a dad jokes generator project using Vuejs and integrating it with this API . However, I've encountered an issue where I'm receiving the same joke repeated in an array instead of just one unique joke. You can view the ...

Behavior of routing not functioning as anticipated

In my app-routing.module.ts file, I have defined the following routes variable: const routes: Routes = [ { path: '', redirectTo: '/users', pathMatch: 'full' }, { path: 'users', component: UsersComponent }, ...

The insecure connection to http://bs-local.com:3000 has prevented access to geolocation

Hi everyone, I hope your day is going well. I could really use some assistance with an issue I've run into. I'm currently trying to test my React web app on BrowserStack's mobile screens, but I am doing the testing locally using localhost. ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

Having trouble with displaying a Bootstrap modal in HTML and CSS?

I am new to programming and facing a challenge with my modal not displaying as expected. Instead of appearing in a popup, it is showing on the page itself. I really need help finding a solution for this issue. Any assistance would be highly appreciated. Be ...

Issue with height in self-invoking function not functioning correctly

Issue with height not functioning correctly inside self-invoking function, but works fine within (document).ready(function() (function($){ var clientHeight = document.getElementById('home').clientHeight; alert(clientHeight); })(jQuery); <di ...

The remove() function is failing to eliminate the element from all parent elements with the same class

I have a bunch of Wordpress posts. When the browser size is reduced to a certain point, I must relocate one specific element from each post to another element as per the design requirements. Here is the code I am using to iterate through each post and mov ...

Uh-oh! Major issue: CALL_AND_RETRY_LAST Allocation was unsuccessful - system is low on memory

I'm experiencing an issue when trying to download a CSV file. It works fine for 40,000 records but runs into a "process out of memory" error when attempting to download 80,000 records via the API. Can someone please assist with this problem? app.ge ...

Generate a main array containing nested arrays made up of individual values

Challenge: I am facing an issue where I have a series of numerical values separated by commas that I need to convert into an array. Each pair of values should be nested within the main array to represent drawing vertices. How can I tackle this challenge ...

Using JavaScript (AJAX), learn the process of incorporating XML data within HTML files

I'm relatively new to HTML and I'm attempting to create a self-contained HTML page that includes all necessary CSS, data, and JavaScript within the file itself. While I understand that this will result in a rather messy HTML document, it is essen ...

Leveraging Django template tags in JavaScript

Currently working on a project that does not have a slug field, and this value is created in the template using: {{ n.title|slugify }} I need to incorporate the slug into a jQuery function, but the variable always remains empty: $("select#model").click( ...

JQuery is failing to properly return the string containing special characters like apostrophes

Storing the name "Uncle Bob's Organic" in the data-Iname attribute caused a retrieval issue, as it only retrieved up to "Uncle Bob". Here is the process used for retrieving the value from the data-Iname: var itemName = $(this).attr("data-Iname"); T ...

Is there a method available to retrieve the data values stored within these objects?

Looking at the image below, I have data that includes a Data array in JSON format. https://i.sstatic.net/WHdUw.png The Data array contains key values such as condition_type and other related values. In order to extract individual values, I am using the ...

Retrieve JSON data with a GET request and populate an array with the results before returning

Recently, I delved into using the mobile framework LungoJS. Although my experience with JavaScript is limited, I am determined to make changes to the following original code: ORIGINAL.JS var mock = function() { var mock = []; for (var i=1 ...

The placement of the button is not correct and should be adjusted to the proper position

I have created a webpage with two distinct sections, each occupying the height of the viewport. The first section contains a 'work' button in the center. Upon clicking this button, it disappears and is replaced by some links. The same functionali ...

I have to ensure that a plugin is only loaded once its dependency has been loaded with RequireJS

Currently, I am utilizing the jquery.validationEngine.js plugin and facing an issue. It seems that jqueryValidateEnglish is unable to function properly unless jqueryValidateEngine is loaded beforehand. In my code for jquery.wrapped.validationEnglish2.js, ...

Angular code is malfunctioning and not delivering the expected results

I currently have setup the code below: var videoControllers = angular.module('videoControllers', []); videoControllers.videoControllers('VideoDetailController', function($scope, $routeParams, $http){ $http.get('http://localho ...

Discover the sub strings that fall between two specified regular expressions

I am looking for a way to extract substrings from a string that are between two specified regex patterns. Here are a few examples: My $$name$$ is John, my $$surname$$ is Doe -> should return [name, surname] My &&name&& is John, my & ...

Having trouble with Angular JS's ngRoute feature not functioning properly

I've been struggling with my ngRoute implementation. I seem to be unable to load the 'ngRoute' module for some reason. Whenever I run this code, I just end up with a blank page. Below is my app.js file: var app = angular.module('tutor ...