Loading google maps markers dynamically with ajax requests

I'm in the process of plotting around 120 markers on a Google Map by utilizing an ajax populated array containing google.maps.LatLng objects

Here is my script

<script type ="text/javascript">
    $.ajaxSetup({
        cache: false
    });

    var gMapsLoaded = false;
    var latlng = [];
    var returnValue;
    var marker;
    var xmlDoc;

    // Ajax request to populate latlng array with LatLng objects
    $.ajax({
        type: "POST",
        url: "map.aspx/getLatLng",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            xmlDoc = $.parseXML(response.d);
            $(xmlDoc).find("Table").each(function () {
                latlng.push(new google.maps.LatLng($(this).find("lat").text(), $(this).find("lng").text()));
            });
            //alert(latlng.length.toString());
        },
        failure: function (response) {
            alert(response.d);
        },
        error: function (response) {
            alert(response.d);
        }
    });

    // Google Maps callback and initialization
    window.gMapsCallback = function () {
        gMapsLoaded = true;
        $(window).trigger('gMapsLoaded');
    }
    window.loadGoogleMaps = function () {
        if (gMapsLoaded) return window.gMapsCallback();
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type", "text/javascript");
        script_tag.setAttribute("src", "http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    }

    $(document).ready(function () {
        function initialize() {
            var mapOptions = {
                zoom: 8,
                center: new google.maps.LatLng(24.678517, 46.702267),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById('map'), mapOptions);

            // Loop through latlng array and create markers
            for (var i = 0; i < latlng.length; i++) {

                marker = new google.maps.Marker({
                    map: map,
                    position: latlng[i]
                });
                var infowindow = new google.maps.InfoWindow({
                    content: 'Location info:<br/>Country Name:<br/>LatLng:'
                });
                google.maps.event.addListener(marker, 'click', function () {
                    // Calling the open method of the infoWindow 
                    infowindow.open(map, marker);
                });
            }
        }

        $(window).bind('gMapsLoaded', initialize);
        window.loadGoogleMaps();
    });


</script>

Html

<div id ="map"   style="width:850px; bottom:20px;  height: 500px;">
</div>

I feel like I might be overlooking something Do I need to convert the latlng array of google.maps.LatLng objects to LatLng before assigning it to position ?

marker = new google.maps.Marker({
                    map: map,
                    position: latlng[i]
                });

Your assistance would be greatly appreciated, Thank you in advance,

Answer №1

It seems like the issue lies in overlooking the asynchronous nature of the ajax request.

You should construct the markers after the ajax request has finished.

Place your for each loop within a function and invoke it at the end of your on success ajax callback.

Additionally, ensure that you load the ajax after Google Maps has loaded to create Google LatLng objects successfully since the Google Maps library may not have been fully loaded yet.

Without rewriting everything, this approach might work:

$.ajaxSetup({
    cache: false
});

var gMapsLoaded = false;
var latlng = [];
var returnValue;
var marker;
var xmlDoc;

window.gMapsCallback = function () {
    gMapsLoaded = true;
    $(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function () {
    if (gMapsLoaded) return window.gMapsCallback();
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type", "text/javascript");
    script_tag.setAttribute("src", "http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}

$(document).ready(function () {
    function initialize() {
        var mapOptions = {
            zoom: 8,
            center: new google.maps.LatLng(24.678517, 46.702267),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map'), mapOptions);

 $.ajax({
    type: "POST",
    url: "map.aspx/getLatLng",
    data: '{}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        xmlDoc = $.parseXML(response.d);
        $(xmlDoc).find("Table").each(function () {
            latlng.push(new google.maps.LatLng($(this).find("lat").text(), $(this).find("lng").text()));
        });

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

            marker = new google.maps.Marker({
                map: map,
                position: latlng[i]
            });
            var infowindow = new google.maps.InfoWindow({
                content: 'Location info:<br/>Country Name:<br/>LatLng:'
            });
            google.maps.event.addListener(marker, 'click', function () {
                // Calling the open method of the infoWindow 
                infowindow.open(map, marker);
            });
        }

    },
    failure: function (response) {
        alert(response.d);
    },
    error: function (response) {
        alert(response.d);
    }
});
    
    }

    $(window).bind('gMapsLoaded', initialize);
    window.loadGoogleMaps();
});

Answer №2

After initializing the map, I made sure to move xml processing to ensure that every marker is in its correct place.

$(document).ready(function () {
        function initialize() {
            var mapOptions = {
                zoom: 8,
                center: new google.maps.LatLng(24.678517, 46.702267),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById('map'), mapOptions);


            xmlDoc = $.parseXML(stringxml);
            $(xmlDoc).find("Table").each(function () {
                marker = new google.maps.Marker({
                    map: map,
                    position: new google.maps.LatLng($(this).find("lat").text(), $(this).find("lng").text())
                });
                var infowindow = new google.maps.InfoWindow({
                    content: 'Location info:<br/>Country Name:<br/>LatLng:'
                });
                google.maps.event.addListener(marker, 'click', function () {
                    // Calling the open method of the infoWindow 
                    infowindow.open(map, marker);
                });
            });





        }

        $(window).bind('gMapsLoaded', initialize);
        window.loadGoogleMaps();
    });

This adjustment ensured that each marker was properly placed on the map.

Thank you for your help!

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

What tool can be used for formatting and syntax highlighting when working with ejs (embedded javascript) templates?

When working on my project, I utilize EJS as the express templating engine. While it is user-friendly and efficient, I have encountered difficulties when it comes to editing files - the text highlighting could be better, and I have not been able to find an ...

Using CodeIgniter's AJAX and JSON functionality, dynamically change the color of a div based on the

Can someone help me with an ajax beginner question? I have a table in my database called companies with columns: id, company_name, select_button, status Whenever a user clicks the select_button on a company row, the status changes to 2 without any issues ...

Struggling to store information in a MongoDB database within my MEAN Stack project

After successfully creating a collection for user LOGIN/LOGOUT and managing to store and retrieve data using Express app and mongoose, I encountered an issue when trying to create another collection. Despite successfully creating the collection, the data w ...

Exploring the Fusion of Material UI Searchbox and Autocomplete in React

Looking for help with my AppBar component from Material UI. I want the Searchbox field to function similarly to what is seen on https://material-ui.com/. It should appear as a Searchbox but display selectable options like Autocomplete after entering input. ...

Is Grouping Together Installed Private Modules Possible?

Exploring a modular JavaScript approach in my upcoming project is a new concept for me. I would prefer explanations to be simple due to my limited experience. I have uploaded my private package on npm: @name/package-name The private package contains mul ...

Trouble experienced with the window.open() function on Safari

When using Safari, it can sometimes block the opening of a new tab through the window.open() function during an ajax call. To bypass this blocking, we must first call window.open() to open a new tab before making the ajax call. Refer to this Stack Overflow ...

Ditch the if-else ladder approach and instead, opt for implementing a strategic design

I am currently working on implementing a strategic design pattern. Here is a simple if-else ladder that I have: if(dataKeyinresponse === 'year') { bsd = new Date(moment(new Date(item['key'])).startOf('year&apos ...

Using Javascript/HTML to enable file uploads in Rails

I'm currently facing an issue with uploading and parsing a file in Rails, as well as displaying the file content in a sortable table. I followed a tutorial on to get started. This is what my index.html.erb View file looks like: <%= form_tag impo ...

JavaScript believes that the function is not defined, despite its clear existence

This question pertains to an issue regarding the recognition of Bookshelf.js model function as a function. The error message "Function is undefined, Bookshelf.js model function is not being recognized as a function" arises when trying to POST to the login ...

using jquery, how can you send multiple parameters in an ajax request

Hello and welcome! I'm having trouble passing parameters through an ajax URL. I am attempting to send multiple data using the jQuery $.ajax method to my PHP script, but I can only pass a single data item when concatenating multiple data entries toget ...

Confusion arises from conflicting Vue component script indentation guidelines

As I work on setting ESLint rules for my new Vue project, I am extending both eslint-plugin-vue and airbnb. All is well except for one issue - the indentation of the tag inside Vue components. The usual accepted format looks like this: <script> ex ...

The repeated execution of a Switch Statement

Once again, I find myself facing a puzzling problem... Despite making progress in my game, revisiting one aspect reveals a quirk. There's a check to verify if the player possesses potions, and if so, attempts to use it involves calculating whether the ...

What could be causing the lack of functionality for my button click in my JavaScript and HTML setup?

Currently, I am attempting to implement a functionality where I have two buttons at the top of my page. One button displays "French" by default, and when I click on the "English" button, it should replace the text with "French" using show and hide methods. ...

Is there a way to handle templates in AngularJS that is reminiscent of Handlebars?

Is there a way to handle an AngularJS template using a syntax similar to Handlebar? <script type="text/ng-template" id="mytemplate"> Name is {{name}} </script> I know how to retrieve the template using $templateCache.get('mytemplate&ap ...

Switching from PHP to JavaScript before returning to PHP to establish and manage sessions

Currently, I am in the process of resolving an issue I am facing. The problem arises when utilizing the following code for someone trying to sign into the admin panel: <script> function myFunction() { //alert('you can type now, end ...

Monitor when users enter commas into input fields in AngularJS

My current challenge involves monitoring user input in a text field and validating the input when a comma is typed, instead of using ng-click="action()". I am looking to implement something like Comma-Typed="action()", but my attempts with ng-change and sc ...

Modify the class of the focused element exclusively in Angular 2

I'm working on a project that involves several buttons and div elements. Currently, the divs are hidden, but I want to be able to reveal a specific div when its corresponding button is clicked. For example: If you click the first button, only the fir ...

Issue with Material UI select component not displaying the label text

I've been struggling with Material UI's "Select" for quite some time now - spent about 10 hours trying to make it work the way I want. Any help would be greatly appreciated. This question is connected to a previous one: Select MenuItem doesn' ...

Ways to stop click propagation in the case of a parent anchor link containing a button among its children

Every time I click on the Link parent, it triggers a click event on the button as well. I want these events to be independent. <Link className="product-item__link" to={`/products/${product.category}/${product.id}`} > <div className ...

Error: The getter callback for the component `RNCSafeAreaProvider` must be a function, but it is currently undefined

After attempting to update my React Native app's dependencies using npm update, chaos ensued. To rectify the situation, I reverted back to the previous package-lock.json, deleted the node_modules folder, and re-ran npm i. Surprisingly, instead of res ...