Tips for transferring variables to my callback function or something similar

I'm facing a challenge with passing the markersArray to the callback function in order to push the results into the relevant array. The issue arises when trying to request nearby amenities for each filter and store them in separate arrays as per the comments in the code.

Despite numerous attempts, I haven't been able to find a solution yet.

Any help or suggestions would be greatly appreciated.

Edit: To clarify, I need to iterate through the filters 4 times and collect the results in 4 different arrays.

Answer №1

Instead of directly passing the callback function reference, consider using an IIFE. This way, the IIFE takes makersArray as an argument and returns a function that will serve as the callback. Within this function, the arguments passed to the IIFE invocation will be accessible.

  for (i = 0; i < filterArray.length; i++) {

    //...

    service.nearbySearch(request, ((markersArray, counter) => 
      (results, status) => {
         // markersArray can be accessed here
         // utilize results[counter] ...
      }
    )(markersArray, i));

  }

Edit: makersArray => markersArray

Update: Since an async function (service.nearbySearch) is being called inside a for loop, it's necessary to also pass the loop counter into the IIFE. In this scenario, use counter rather than i within the callback function.

Answer №2

Upon analyzing your code, I have noticed another method to retrieve the markersArray from the caller during debugging. However, it is unclear how you intend to display the markersArray on your map. Once you have implemented this into your code successfully, kindly share the working version for further assistance in comprehension.

GIT Repository Link: https://github.com/helloritesh000/how-to-pass-variable-to-my-callback-function-or-similar

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Interactive Map</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        html, body {
        margin: 0;
        }
        #map {
            height: 400px;
            width: 100%;
        }
    </style>
</head>
<body>

    <input id="mapLatitude" type="hidden" value="51.571527">
    <input id="mapLongitude" type="hidden" value="-0.149113">
    <input id="amenityType" type="hidden" value="school">
    <input id="markerIcon" type="hidden" value="assets/img/mapMarkerIcos-schools.png">

    <div id="map"></div>

    <button class="mapFilter" data-filter="school">schools</button><br>
    <button class="mapFilter" data-filter="restaurant">restaurants</button><br>
    <button class="mapFilter" data-filter="subway_station">stations</button><br>
    <button class="mapFilter" data-filter="convenience_store">shops</button><br>

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBNPO77AnQOdXcUhisHtfu_RP0Ha3bZKn8&libraries=places"></script>
    <script src="assets/js/main.js"></script>


    <script type="text/javascript">
        /* 
          Remaining code with potential improvements goes here
        */
    </script>
</body>
</html>

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

Concern with Json Data Structure

How can I display data in the following layout: the datas that published today: data1, data2, the datas that published yesterday: data1, data2 If I receive the data in JSON format, what should the JSON structure look like to achieve this format? The HTM ...

Using the `ng-repeat` directive as an argument in a Javascript function

I am struggling to pass the ng-repeat element to a JavaScript function, but it's not working as expected. <tr ng-repeat="x in myArry"> <td><input type="text" value="{{x.firstname}}" id="{{x.firstname}}{{$index}}" onblu ...

Designing the presentation of two overflowing text containers positioned next to each other

Hey there, I'm currently working on styling something that shows both the user's username and the title of an item on the same line, similar to how it's done on GitHub: username / title I want to make sure that if the combined width of the ...

Can jQuery be used in Chrome Extensions?

I am facing an issue with my extension. Do I need to declare permissions? The "code:" line is not working in the background file. Here is the code from the Background File: chrome.browserAction.onClicked.addListener(function(tab) { // No tabs or host p ...

Exploring Arrays of Objects in Couchbase

How can I extract a specific key-value pair from an Object of Array within a JSON object using N1QL for Couchbase on Couchbase Server? Here is the structure of my JSON: { "A":{ "B":{ "C": { ...

Utilizing useState() to manage active link state in Navigation bar component

Learning react and new to the framework. Trying to create a responsive navbar component with material-ui. Works fine on medium devices but struggling with updating active link on smaller devices. Navbar.js ... SideDrawer.js ... C ...

Encountering an unforeseen change in the "buttonText" attribute

I've developed a simple Vue.js component for a button. When the button is clicked, it should display the text "I have been clicked." It does work as expected, but I'm also encountering an error that reads: 49:7 error Unexpected mutation of "but ...

Extracting data from a PHP array and generating JSON output

I'm a beginner in PHP and I'm attempting to develop a web service. I have a function that selects a certain number of rows from a database, and it works correctly (returning 22 rows). However, when I call this function from my index.php page and ...

Obtain the HTML5 data attribute from an event directly in the code

I am attempting to access the data attribute in the following manner (my doctype is html5): <a href="#my-link" data-zoom="15" onclick="alert(this.data-zoom); return false;">link</a> However, I am encountering an e ...

Limit the implementation of Angular Material's MomentDateAdapter to strictly within the confines of individual

Within my app, I have several components that utilize the mat-datepicker. However, there is one component where I specifically want to use the MomentDateAdapter. The issue arises when I provide it in this one component as it ends up affecting all the other ...

What is the best way to incorporate various variables into the heading of my plot design?

I need the title to display as: "Target Electron Temperature =Te_t [ev] Target Density=n_t [m^-3]" The values of Te_t and n_t represent the input variables. While I can successfully generate the title with one variable, I am having trouble including bot ...

Dividing a string in JavaScript to generate fresh arrays

I am currently dealing with the following string: "ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"~100000000,1000048,0010041,1,1,1,1~100000001,1000050,,2,0,2,1~100000002,1068832,0 ...

display hidden sections, not entire pages

Similar Question: Printing content of <div id=printarea></div> only? Hello everyone, We are all familiar with the window.print() function. If we have a div containing some content, how can we print it? ...

Chart.js is failing to display the chart when integrated with RequireJS

I have been attempting to display a chart using Chartjs and Requirejs, but unfortunately, it is not rendering properly and no error messages are being displayed. I am aware that I may be overlooking something simple due to fatigue, but I am unable to pinpo ...

Absence of event firing in .on method in Asp.NET Core 6 when using JQuery

I am currently working on an ASP.NET Core 6 application that utilizes JQuery. Here is the JQuery code snippet I have implemented in my page: @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } ...

Save checkbox selection in PHP Session and display it

I am facing a challenge in saving a group of checkboxes in a session variable to display them on a different page. For instance, if a user selects the first two checkboxes on page 1, the redirected page 2 should display "apple" and "banana". Form: <f ...

Can you provide an alternative code to access an element with the id of 'something' using vanilla JavaScript instead of jQuery's $('#something') syntax

Why am I seeing different console output for $('#list') and document.getElementById("list")? Here is the console printout: console.log($('#list')); console.log(document.getElementById("list")); However, the actual output in the cons ...

The Material-UI selector isn't functioning properly for me

I recently tried to incorporate a material-ui selector example into my project by referring to the code fragment obtained from an example on Github. import React from "react"; import {withStyles} from "material-ui/styles"; import Select from "material-ui/ ...

Dealing with errors in a sequelize ORM query: Tips and tricks

Currently, I am implementing Sequelize ORM in my Node/Express project using Typescript. Within the database, there is a 'users' table with a unique column for 'email'. As part of my development process, I am creating a signIn API and ...

Using Angular 4 with Bootstrap dropdowns necessitates the use of Popper.js

I recently created an Angular 4 CLI app. After executing the following command: npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066469697275727467764632283628362b64637267">[email protected]</a> jquery ...