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

Ways to conceal a div element when the JSON data does not contain a value

If the value in "desc" is empty, then hide <div24> and <popup-desc>. html <div class="popup"> <div class="popup-top" style="background-color: '+e.features[0].properties.fill+';"> ...

Passing a JSON file name as an argument to a command line in Node.js

When I run app.js using the command node app.js, it will execute const inputData = require('./input.json'); Now, my question is - can I pass the file name as an argument to const inputData = require('./file.json'); directly from the co ...

What is the process for converting an <input type="file> into a base64 string?

Currently, I'm attempting to send an image to my express backend by including the image directly in the post request body. var imgValue = document.getElementById("image").value; Within my post request: body : JSON.stringify({ image:imgValue ...

A Step-by-Step Guide to Launching PDF Blob from AJAX Response in a Fresh Chrome Tab

I'm sending a POST request to a server, and in response, I receive a PDF file that is returned as a blob. To handle this blob, I am using the "handle-as='blob'" attribute of iron-ajax (a Polymer element), just to cover all bases. Now, my g ...

Creating curved triangles in React Native is a fun and easy way to add stylish

Hello everyone, I am a newcomer to react native and I am attempting to create the following user interface. Is there any way to create a curved triangle? I have tried but I am unable to curve the edges of the triangle. https://i.stack.imgur.com/vE17U.png ...

Issue with hook not updating when invoked inside useEffect

I'm encountering an issue with updating the state after fetching data from my API. The API response seems to be correct, but for some reason, my weatherData-hook is not getting updated and it returns undefined. Can anyone point out what mistake I migh ...

Retrieve JSON object by matching another JSON property

I am working with an array of id's and their respective contents in a JSON response. My goal is to retrieve the content based on the received id. For instance, if the ID is 1 (returned from the JSON), I aim to access the JSON data using "data.id" (wh ...

Why are my variables resetting in Angular after ngAfterViewInit?

There seems to be an issue with my variables resetting after successfully using them in ngAfterViewInit(). I have a few @ViewChild and regular variables that are utilized or set in ngAfterViewInit. However, when certain events that I added post-initializa ...

Using await outside of an async function is not allowed

When working with a rest api in node.js, I have implemented functionality to automatically resize any uploaded images that are too large. However, I am encountering an error when trying to call my await method. Here is the code snippet: ': await is o ...

Employing parseFloat() and parseInt() functions together with regular expressions in JavaScript for converting a Comma Separated Values (CSV

I've been working on converting a CSV file to a local 2D array and I'm curious if there's a more efficient method of changing strings to floats/int rather than relying on regex paired with parseFloat() / parseInt. Any bright ideas or sugges ...

What steps can I take to completely remove JavaScript from an HTML document?

To eliminate the <script> tags in the HTML, I can utilize regex just like this $html = preg_replace('#<script(.*?)>(.*?)</script>#is','', $html); While this approach works well, dealing with inline JavaScript require ...

AngularJS Default Option Selection

I am encountering some difficulties with the preselection of a select-input in angularJS. The select-box is being populated by an array. <select class="form-control" ng-model="userCtrl.selected_country" ng-options="country.name for country in userCt ...

When using form.serialize() in Django forms, an empty object is being sent

Upon clicking the button, my AJAX request is sending an empty object Object { } instead of form data. The form on my page consists of checkboxes and its HTML structure is as follows: <form method="post" action="" data-id="filter-form"> //Included ...

Managing the sequence of QUnit tests

I have created a website using jQuery and made numerous ajax requests in JSON format. I am interested in performing unit tests to validate the server side requests. Since I used jQuery, I chose qUnit for testing, but I'm facing an issue with the order ...

Issues arise when attempting to use the Android KeyUp, KeyDown, and KeyPress events in conjunction with Angular2

I am encountering an issue where I consistently receive a keyCode of 229 in Android Chrome browsers when running either: <input type="text" (keydown)="testKeyCodes($event)"/> <!-- or --> <input type="text" (keyup)="testKeyCodes($event)"/& ...

Issue with code failing to insert object into an array

I've been struggling to add a group of objects from a JSON file into an array. Despite trying to use the push method, the length of the array remains at 0. I'm puzzled by what could be going wrong. The JSON data is being parsed correctly as I&apo ...

What is the best way to add data to my collection using the main.js file on the server side in a Meteor application

I am a beginner with Meteor and trying to customize the tutorial codes. I have a code that listens for packets on my server-side main.js. Now, I need to store the data printed on the console into my database collection. import { Meteor } from 'meteor/ ...

Tips for executing a never-ending blocking operation in NodeJS?

Currently, I have a collection of API endpoints within Express. One specific endpoint triggers a lengthy process that hinders the flow of other incoming requests in Express. I am determined to transform this process into a non-blocking one. In order to ga ...

The Correct Way to Implement Google ReCaptcha

I've developed a PHP contact form that performs validation using AJAX/JSON on the server side. The errors are then passed to Javascript for display and adjustments to the HTML/CSS. My challenge now is to integrate Google ReCaptcha with AJAX validatio ...

Best method for reverting react-native to previous version

Here's the dilemma I'm facing: I had a functional version of a react-native project that was running smoothly and committed to my git repository. Deciding to upgrade from react-native 0.26.3 to 0.28 led me into a tangled web of dependencies, so ...