The second request made with $.ajax is bypassed

I have been working on integrating the Google Maps JavaScript API and attempting to update a heat map when a user clicks on a specific div element. The latitude and longitude data used for the heatmap are fetched from local JSON files. While I have successfully loaded the web page with the map and heatmap overlay displaying correctly, I encountered an issue when trying to update the heatmap data upon clicking a div – the heatmap simply disappears.

Upon debugging, I found that the $.ajax call within my getPoints(file) function is skipped whenever I invoke getPoints(file) in my onclick listener. Could anyone provide insight into what might be causing this issue? Below is the code snippet:

var map, heatmap;

function initMap() {
    var sanFran = {
        lat: 37.775299,
        lng: -122.432432
    }

    map = new google.maps.Map(document.getElementById('Map'), {
        zoom: 10,
        center: sanFran,
    });

    heatmap = new google.maps.visualization.HeatmapLayer({
        data: getPoints("2016-07-02--11-56-24.json"),
        map: map
    });
};

function getPoints(file) {
    retArr = [];
    var weblink = "http://localhost:8080/trips/" + file;
    $.ajax({
        url: weblink,
        dataType: "json",
        success: function(data) {
            for (var i = 0; i < data.coords.length; i++) {
                console.log(data.coords[i]);
                retArr.push(new google.maps.LatLng(data.coords[i].lat, data.coords[i].lng))
            }
        }
    });
    return retArr;
}

$.each(jsTrips, function(k, v) {
    $("#" + k).on("click", function() {
        heatmap.set('data', getPoints(v));
    })
})

The JSON data structure is as follows:

{
"start_time": some time,
"coords": [{lat, long}, {lat, long}, {lat, long}],
"end time": some time
}

If further details are required, please feel free to ask, and I will update the question accordingly.

Thank you!

Answer №1

$.ajax works asynchronously, so the array returned from getPoints will always be empty because the asynchronous success function runs after getPoints has already finished executing.

To fix this issue, you should reorganize your code as shown below:

var map;
function initMap() {
    var sanFran = {
        lat: 37.775299,
        lng: -122.432432
    }

    map = new google.maps.Map(document.getElementById('Map'), {
        zoom: 10,
        center: sanFran,
    });
};    

function getPoints(file) {
    $.ajax({
        url: `http://localhost:8080/trips/${file}`
        dataType: "json",
        success: rawData => {
            const data = rawData.coords.map(({ lat, long }) =>
                new google.maps.LatLng(lat, lng)
            );
            new google.maps.visualization.HeatmapLayer({
                data,
                map
            })
        }
    });
}
$.each(jsTrips,function(k,v){
    $("#"+k).on("click",function(){
        getPoints(v);
    })
})

Note: This code snippet is provided as-is and has not been tested.

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

Executing axios calls within other axios calls and altering state in React before all calls have completed

Currently, I am working on implementing nested axios calls to create the desired object by making multiple API requests. However, I am facing an issue where the state updates before all requests have finished, causing my table to populate entry by entry ...

Create images from HTML pages with the help of Javascript

Hello there, UPDATE: I am looking to achieve this without relying on any third-party software. My application is a SAP product and installing additional software on every customer's system is not feasible. The situation is as follows:   ...

"Troubleshooting the ineffectiveness of JavaScript's

(After reviewing all questions and answers related to this issue, I have not found a solution that works for me.) Here is the code snippet in question: var timeoutHandle; function showLoader(show) { if (show) { $('.loader').html(&a ...

Calculating the product of two input fields and storing the result in a third input field using a for loop

There's a small issue I'm facing. I have implemented a For Loop to generate multiple sets of 3 input fields - (Quantity, Rate, Price). Using a Javascript function, I aim to retrieve the Ids of 'Quantity' and 'Rate', and then d ...

Rendering elements dynamically using ng-repeat following an AJAX request

Feeling frustrated, I made an $http request ApiService.get_request_params("api/endpoint").then( function(data) { $scope.customers = data }, function(err) { } ); The $scope.customers should be bound to an ng-repeat. I can see the ...

What methods can be used to create data for the child component?

Below is the primary code: import {Col,Container,Row} from 'react-bootstrap'; import {useEffect,useState} from "react"; import AppConfig from '../../utils/AppConfig'; import BB from './BB'; import React from "re ...

Error: The variable 'err' is not declared in this scope.at line app.post

Tools I am Using Windows 10 Firebase (Firestore) Postman JavaScript, Express I'm learning from this video(https://www.youtube.com/watch?v=-vo7cu0xP4I) Situation Description I attempted to make a post request using Postman for testing purposes, b ...

Guide on extracting JSON data from jQuery containing an array in C#

Looking for a way to extract array data from JSON in C#? Here is an example of the AJAX code: $.ajax({ type: "GET", url: "/Weather/GetWeather", data: { "a": ["1,","2&"], "b" : 4 }, success: onSc ...

The React component is being rendered repeatedly

I am new to React and decided to implement some functionalities to enhance my understanding of the framework. Currently, I am working on a search feature that displays results in a table format. Each row in the table has a delete option, which triggers a p ...

achieve precise outcomes using mapping techniques

I am currently learning react.js and encountering an issue with obtaining specific results on the map. Below is the code I am working with: render(){ const friends = [ {id:1, name: 'Dave',age:50}, {id:2,name: 'Kellie',age:42}, {id:3, ...

Adjust the size of the Div and its content to fit the dimensions of

Currently, I have a div containing elements that are aligned perfectly. However, I need to scale this div to fit the viewport size. Using CSS scale is not an option as it does not support pixel values. https://i.stack.imgur.com/uThqx.png I am looking to ...

extracting a JSON array from an API

I'm trying to extract the title from my API using JavaScript and then display it in HTML. api:(https://k0wa1un85b.execute-api.us-east-1.amazonaws.com/production/books) The JSON response is as follows: {"statusCode":200,"body":[{"id":"4f160b1f8693cd ...

Creating web addresses using PHP and AJAX

I have an input field where users can enter text, and upon submitting an ajax request retrieves data from the database using PHP. Everything is functioning smoothly so far. However, once the results are displayed, each item can be clicked to view a more ...

The filter on the mobile version is not displaying correctly

When I select a category in the input filter, only items with the same category are displayed when clicked. However, when I click on "Others" on the desktop version, only rows with that category are shown, but on mobile after resizing and filtering, nothin ...

AngularJS Assessing an Attribute directive following an Element directive

Currently, I am utilizing an angular plugin that can be found at the following link: https://github.com/angular-slider/angularjs-slider The objective is to customize the "legends" produced by the directive. In order to achieve this customization, the dire ...

Scrolling with jQuery just got a sleek upgrade with our new

Can anyone suggest a jQuery scrollbar that resembles the clean black bar found on the iPhone? I need a simple design without visible up or down buttons. Many scripts I came across offer more features than necessary for my project. My div element has a fi ...

The output of new Date() varies between app.js and ejs

app.get("/test",function(req,res){ var d = new Date(); res.send(d); }); When I access mydomain/test, it displays the output "2019-03-19T04:50:47.710Z" which is in UTC. app.get("/testejs",function(req,res){ res.render("testejs");}); Below is the content ...

Enabling Bootstrap modal windows to seamlessly populate with AJAX content

I'm currently in the process of crafting a bootstrap modal that displays the outcome of an AJAX request. Below is my bootstrap code: {{--Bootstrap modal--}} <div id="exampleModal" class="modal" tabindex="-1" role="dialog"> <div class="m ...

Issue with Gulp Watch failing to detect modifications in Browserify files

Currently, I am utilizing the laravel-elixir-vueify npm package for my project. Gulp watch functionality performs as expected when I make changes to files within the "scripts" or "styles" functions. However, there seems to be an issue when it comes to moni ...

Changing colors using JavaScript: A step-by-step guide

Hey there! I'm looking to change the color code in this script from $("#Tcounter").css("color","black") which uses the color word "black", to "#317D29". Can someone help me figure out how to do this? <script type="text/javascript"> $(document). ...