The presence of multiple renderings occurring due to Google Maps InfoBox and an AJAX call

I'm encountering a problem with my implementation of the InfoBox and I'm looking for insights on potential solutions.

Currently, I have around 1000 client-side markers that are dynamically added to the page. They are created using the following code snippet:

 var cir = new google.maps.Marker({
            position: new google.maps.LatLng(l.lat, l.lng),
            map: map,
            icon: icons[l.type].simple
        });
        addClickHandlerAjax(cir, l);
        l.m = cir;

The addClickHandlerAjax method is triggered when a marker is clicked. Here's the basic structure of this method:

function addClickHandlerAjax(marker, l) {

    google.maps.event.addListener(marker, "click", function () {

        if(theInfoWindow){
        theInfoWindow.close();
       // InfoWindow = null;
        }
        //fetch content via ajax
        $.ajax({
            url: 'map/getInfo',
            type: 'get',
            data: {
                'ID': l.f
            },
            success: function (data, status) {
                if (status == "success") {
                    //create infowindow here..
                           theInfoWindow= new InfoBox({
                            content: document.getElementById("infobox-wrapper-hotel"),
                            disableAutoPan: true,
                            enableEventPropagation: true,
                            closeBoxURL: '../assets/images/info-close.png',
                        });
                        theInfoWindow.open(map, marker);
                        touchScroll('rab-scroll');

                });
                }
            },
            error: function (xhr, desc, err) {
                console.log(xhr);
                console.log("Details: " + desc + "\nError:" + err);
            }
        }); // end ajax call
    });
}

The issue arises when users click on multiple markers quickly, causing the infobox of a previous marker to remain open, possibly empty.

Is there a proper way to manage multiple infobox instances by ensuring all infoboxes are safely closed?

This behavior is not observed in this example Jsfiddle

Answer №1

If you're aiming to keep only one InfoBox open at a time, a simple solution is to create a single global InfoBox in the global scope and utilize it for all markers. The example referenced accomplishes this by initializing var ib = new InfoBox(); as the sole global InfoBox.

To tackle slow response times, adjust your ajax processing to handle this delay effectively (specifically closing the current infowindow only upon successful completion of the callback function):

function addClickHandlerAjax(marker, location) {

    google.maps.event.addListener(marker, "click", function () {

        // Retrieve content using ajax
        $.ajax({
            url: 'map/getInfo',
            type: 'get',
            data: {
                'ID': location.f
            },
            success: function (data, status) {
              if (status == "success") {
                // Close the current infowindow only when the AJAX response succeeds
                if(theInfoWindow){
                  theInfoWindow.close();
                }
                // Remove the existing infowindow from the map on successful AJAX response                    
                if (theInfoWindow.setMap) theInfoWindow.setMap(null); 
                // Create a new infowindow here with the retrieved content
                theInfoWindow = new InfoBox({
                   content: document.getElementById("infobox-wrapper-hotel"),
                   disableAutoPan: true,
                   enableEventPropagation: true,
                   closeBoxURL: '../assets/images/info-close.png',
                });
                theInfoWindow.open(map, marker);
                touchScroll('rab-scroll');
              };
            },
          error: function (xhr, desc, err) {
              console.log(xhr);
              console.log("Details: " + desc + "\nError:" + err);
          }
        }); // end ajax call
    });
}

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

Having trouble interpreting the response using jQuery

Upon running my PHP script, I am receiving the following response. PHP: <?php $con = mysqli_connect("localhost","root","pass","products"); if(mysqli_connect_errno()) { echo "Failed to connect database, please check with your administrator. Error ...

The error message TS2322 in MUI v5 states that the property 'fullWidth' is not found in the type 'IntrinsicAttributes & { theme: Theme; } & { children?: ReactNode; }'

As a user of MUI v5, I have implemented a straightforward FormControl as seen below. It is important to note that the property fullWidth is supported according to the official documentation. import React, { PropsWithChildren } from 'react' import ...

Using Vue.js to iterate over a list of items and accessing specific array objects by their unique identifier

My JSON array of objects has the following structure: https://i.sstatic.net/1IUVE.png When generating a <ul>, I need to fetch an ID from an API for each <li>: <ul> <li v-for="genre in movie.genre_ids"> {{ genre }} ...

Dropdown menu utilizing processing API and interacting with AJAX and DOM manipulation

My API data is not showing up in the dropdown menu. If I use ?act=showprovince, I can see the result. example.html <head> <link rel="stylesheet" type="text/css" href="css/normalize.css"> <link rel="stylesheet" type="text/css" hr ...

Can JavaScript be used to modify the headers of an HTTP request?

Can JavaScript be used to modify or establish HTTP request headers? ...

"Unable to move past the initial segment due to an ongoing

My portfolio webpage includes a "blob" and "blur" effect inspired by this YouTube video (https://www.youtube.com/watch?v=kySGqoU7X-s&t=46s). However, I am encountering an issue where the effect is only displayed in the first section of the page. Even a ...

Execute a Node script using PHP exec, retrieve the data in PHP, and then apply the finally method

I'm working on a PHP script that utilizes the exec function to run a Node script and then return some data back to the PHP script. The challenge I'm facing is finding a way to send the data back to PHP without having to wait for the cleanup code ...

tips for storing user input into an array

I am currently developing a calculator that uses Json data. The goal is to retrieve the Grid Code associated with a specific longitude and latitude input. However, I am encountering an issue where the result returned is 0, indicating that the value of the ...

Unable to retrieve the user ID from a Discord username using Discord JS

let string = `${args[1]} ${args[2]}` console.log(string) const idofuser = client.users.cache.find((u) => u.username === `${string}`).id I am facing an issue with DiscordJS where it says "cannot read property 'id' of undefined" when trying to ...

Refresh the Server Component once data has been modified by the Client Component within Next.js

I am still grappling with this specific scenario and trying to figure out the best approach in Next.js 13. Can anyone provide guidance on the correct way to handle this? In a Server Component, I have a list of users being displayed, leveraging MongoDB, as ...

Configuration file stored within the node_modules directory

I have developed a generic npm package that contains my business logic. However, I require access to some information stored in my google cloud storage configuration files. How can I retrieve this data when my package is located within the node_modules fol ...

Is there a way for me to gain access to the ng-repeat scope?

I have a scenario where my ng-repeat generates different elements and I need to perform certain operations, such as creating variables, within the scope of the ng-repeat. Is there a way to access the specific ng-repeat scope? How can I achieve something ...

Personalize the color scheme for your timeline paper

I am interested in customizing this specific example of a personalized timeline: import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Timeline from '@material-ui/lab/Timeline'; import Timeli ...

How can I modify the ngx-datatable pager component to display text instead of icons and include a totalVisible property?

I am currently customizing the datatable-pager in ngx-dataTable and have been successful in adding footers and pagers. However, I am facing two issues that need resolution: How can I display text instead of icons for the prev/Next/First and Last buttons? ...

Challenge encountered when attempting to remove elements from an array within a for loop

There seems to be an issue with deleting elements from an array within a for loop. var div = document.querySelector('div'); var array = [ "iPad", "iPod", "iPhone" ]; for (let i = 0; i < array.length; i++) { let p = document.createElement ...

Compatible with pure vanilla JavaScript, but not jQuery

I am currently facing an issue with attaching VKI (Virtual Keyboard Interface) to an element that is dynamically added to the DOM using JavaScript. The scenario involves a table with initially only one row, along with "Add Row" and "Delete Row" functionali ...

Enhance the current MultiSelect object by incorporating JQuery MultiSelect

Is there a way to detect changes on a JQuery MultiSelect in order to trigger an update elsewhere? The typical javascript onchange method does not seem to work because the select itself does not change. However, I came across a method called "beforeclose" t ...

Issues verifying the selected value for the ajax request

One of the challenges I'm facing is related to a form that requires specific user selections. If the user chooses a value of 1, the form can be submitted without any additional steps. However, if they select values 2 or 3, they must then choose an opt ...

Guide to verifying Regular Expressions for text fields in JSP with JavaScript

Need help with validating the firstname using regex. The javascript code provided generates an error if the value length is 0, however, even after entering a correct firstname format based on the regex, it still shows 'First name invalid'. I susp ...

Deleting a DOM element within an element that has been created by an external script

On a webpage, I have third-party ad content that is generated by an external script. This content has a delay in loading. My goal is to eliminate a line break from the ad content, but this can only be done once the external script finishes loading and all ...