Utilizing Google Maps v3 to Add Markers Post Completion of AJAX Request

My current challenge involves loading markers on a Google map using an ajax call. The issue I am facing is that the ajax call takes a long time to complete, but the map loads before it finishes. As a result, I do not see the markers on the map.

Below is the code snippet:

<script type="text/javascript">
var map;
function initialize() {
    var myLatlng;
    var mapOptions;     
    myLatlng = new google.maps.LatLng("29.9844", "-95.33389");
    mapOptions = {
                zoom: 12,   
                center: myLatlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP };

   map = new google.maps.Map(
   document.getElementById("map-canvas"), mapOptions);
 google.maps.event.addListenerOnce(map, 'idle', function() {
         getRegions( function( result ) {
            alert("getRegions callback return value : " +  result.regionList );
          addMarkersAtRegionCenter(result );
        });
    });
}
</script>
function addMarkersAtRegionCenter(result) {
    var length = result.regionList.length;
     for(var i=0; i<length; i++)
     {
        var image = result.regionList[i].imageIcon;
        var marker = new google.maps.Marker({
        position: new google.maps.LatLng(result.regionList[i].centerLatitude,result.regionList[i].centerLongitude),
                  icon: image,
                  map: map
});

google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() {
                    window.location.href = marker.url;
               }
             })(marker, i));
     }
 }
function getRegions(regions, callbackRegions) {
  $.ajax({
        type : 'POST',
        url : 'getRegions.jsp',
        data : {regions: regions},
        dataType: "json",
        success : function(result, textStatus, jqXHR) {
            // invoke the callback function here
               callbackRegions(result);
         },
        error: function (result, textStatus, errorThrown) {
            // invoke the callback function here
               callbackRegions(result);
        }
 });
}

Despite receiving response from the server and being able to view it in the browser, I am unable to display this response in the alert message within the above code block. Here's the response I received:

{"regionList":[{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578}]}

If you have any insights on what might be causing this issue, your assistance would be greatly appreciated.

Answer №1

Upon reviewing your code, I noticed an issue with the getRegions function. You are only passing in the callback function when you call getRegions.

getRegions( function( result ) {
            alert("getRegions callback return value : " +  result.regionList );
          addMarkersAtRegionCenter(result );
        });  

The problem lies in the fact that the function expects two parameters:

function getRegions(regions, callbackRegions)...

In your success function, you are calling callbackRegions but it will be undefined.

  1. To address this, create a separate callback function named regionsLoaded:

    function regionsLoaded(result)
    {
        alert("getRegions callback return value : " +  result );
    }
    
  2. Modify your getRegions function as follows:

    function getRegions(callbackRegions)...
    
  3. Then, make your call like this:

    google.maps.event.addListenerOnce(map, 'idle', function() 
         {
        var regions =  getRegions(regionsLoaded);                       
    });
    

For further assistance, refer to this JS fiddle: https://jsfiddle.net/loanburger/ugebw5hb/

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

Updating dynamic content in IBM Worklight V6.1 with jQuery Mobile v1.4.3 requires waiting for the DOM to load

I need to dynamically update the content of a div within my HTML page structure. <!DOCTYPE HTML> <html> ... <body> <div data-role="page"> <div data-role="header"> //Image </div> <!-- Th ...

Ever since updating my jQuery version to 3.2.1, my ajax code seems to have stopped functioning properly

My program's ajax functionality was running smoothly with jquery version 1.7, but when I updated to version 3.3.1, the ajax part stopped working. I made sure to attach the ajax portion of my code after updating the jQuery version. In the PHP file, I s ...

The system encountered an error while trying to access the property "slug

I am currently working on a project that involves using next.js and wordpress. I have set up my api.js file, but I encountered an issue when trying to access the [slug] property from another component. The error message displayed is "Typerror: Cannot read ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

Ensuring the validity of multiple email fields

I am utilizing a validation script created by Joren Rapini for my online form. Visit Joren's Website for more information. The current code allows me to validate one email address, but I need to validate two different email fields in the form. Does a ...

Retrieving information from the server through an AJAX request

I have set up a xampp server on my localhost and placed a text file named "a.txt" in the htdocs folder. Now, I am attempting to retrieve data from this text file on the server using an HTML file located on my desktop. <!DOCTYPE html> <html> ...

Using Google ReCaptcha without the need for a PHP plugin

While I understand the cross-domain error when using ajax to fetch information from another website, jQuery suggests that using a jsonp request can solve this issue. However, I am facing challenges in implementing this when trying to display recaptcha. Unf ...

Automatic File refresh in Javascript without page reload

My webpage includes a javascript file that is called in the head tags of the document. I need this javascript file to reload every 30 seconds. In my research, I found issues with pulling a locally stored copy of the file and potential cross-browser compat ...

Remove HTML code through an AJAX call

My HTML code utilizes ajax and jQuery to display a user's tweets, user_id, and the amount of tweets through an ajax request via an html form. The issue I am facing is that when I send new data, the old tweets are not being deleted. For example, if I r ...

Click to collapse the accordion menu on the following page

I have created an Accordion-based menu in a file called menu.php. For example: menu.php <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingOne"> <h4 class="panel-title"> <a role="butt ...

Decimal values in a Razor Pages application using .NET 7 will be bound to the Dutch Culture setting and

I am currently working on a website that utilizes .NET 7 and Razor pages. In my specific scenario, I have a table with multiple rows where I need to update the backend whenever a decimal or DateTime value changes. The culture setting is nl-NL, resulting i ...

The JQuery.ajax() function fails to return a response body

I am currently in the process of developing a SmartTV application that needs to retrieve its channel list from a specific URL. However, I have encountered an issue where I am not receiving the expected response text despite seeing the correct content leng ...

Troubleshooting script error: Dealing with Ineffective Redirects

I am currently using a JavaScript code that allows users to jump to a directory by typing its name. Here is how it functions: If the input field is left empty, the user will be directed to a page called "error.html" which displays the message "This field ...

displaying user-entered data using the AJAX method and presenting it in PHP

Here is the input I want to display: <textarea id="mytext" class="txtarea" name="in_content" cols="120" rows="15"><?php echo $term;?></textarea> Below is my AJAX code that retrieves the value from the textarea above: $('#spdf-form ...

Using a relative path in Ajax is ineffective

I am facing an unusual issue with AJAX. The HTML page I am working on is calling an AJAX function from this location: public_html/test/books.html The AJAX file that needs to be called is located here: public_html/lists/include/vote_up.php I have tried ...

Divide the promised variable into separate named variables

Here is a code snippet that I am working with: Promise.all( categories.map(category => Collection.find({ category })) ).then(items => { return items }) Currently, the output is an array with the same length as categories, where each element is ...

Adjust the level of output from webpack when initiating the vue-cli-service serve programmatically

My current challenge involves executing the vue-cli-service serve command within a Node.js application as shown below: const Service = require('@vue/cli-service'); const service = new Service(process.cwd()); service.init("development"); service. ...

Collapse or expand nested rows within a dynamic table using Bootstrap Collapse feature

I am currently working on creating a dynamic leaderboard table for a sports league using data from a SQL database. The league consists of multiple teams, each team has different players (with some players belonging to more than one team), and players earn ...

The input field for Google Places Autocomplete now includes the code "display: none"

I'm currently working on an AngularJS application and have implemented this directive to enable Google Maps API places autocomplete in the input field below. <div> <input type="text" autocomplete="off" g-places-autocomplete ...

What is the best approach to assigning PHP variables in this specific scenario?

I need help with creating a PHP AJAX post request without refreshing the page. Here is the code I have so far. It successfully returns the value and displays it in <div id="msg"></div>, but I am struggling to assign this value to a PHP variable ...