javascriptcode to execute before loading google maps

I am facing an issue with displaying markers on Google Maps. The problem arises when the array with latitude and longitude values is constructed through an Ajax request. Due to the map being loaded before the initialization of the array, I am unable to see the markers. I suspect that this is the root of the issue but I am uncertain. Any assistance in resolving this matter would be greatly appreciated.

<script>
    $(document).ready(function() {
        setVariable('<?php echo $_SESSION["token"]?>');
    });
</script>


<script defer
        src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXX&callback=initMap">
</script>


coord = new Array();

function setVariable(token) {

format="text/plain";
$.ajax({
url: BASE_URL + "reports",
type: "GET",
contentType: "application/json; charset=utf-8",
headers: {'x-access-token': token},
cache: false,
success: function(data){
if (data.success){
$.each(data.data.reports, function (i, item) {
coord[i] = [ data.data.reports[i].lat , data.data.reports[i].lng ] ;
});
console.log(coord)
}else{
alert(data.error.message);
}
},
error: function(data){
console.log(data);
}

});
}

function initMap() {

var myLatLng = {lat: 43.1107168, lng: 12.3908279};

var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: myLatLng
});

var marker, i;
for (i = 0; i < coord.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(coord[i][0], coord[i][1]),
map: map,
title: 'Hello World!'
});
}

}

Can someone guide me on how to resolve this issue?

Thank you for your help.

Answer №1

To successfully integrate the map markers, a restructuring of the code is necessary. The markers should only be added to the map after fetching the lat/long data via an AJAX request. Here's a suggested approach:

<script defer
    src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXX&callback=initMap">

/*
A global variable will hold a reference to the google map object.

It will be initialized upon loading the Google Maps script and calling the initMap function subsequently.
*/

var GoogleMap;

coord = new Array();

function setVariable(token) {

format="text/plain";
$.ajax({
    url: BASE_URL + "reports",
    type: "GET",
    contentType: "application/json; charset=utf-8",
    headers: {'x-access-token': token},
    cache: false,
    success: function(data){
        if (data.success){

            $.each(data.data.reports, function (i, item) {
                coord[i] = [ data.data.reports[i].lat , data.data.reports[i].lng ] ;
            });
            console.log(coord)

            var marker, i;
            for (i = 0; i < coord.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(coord[i][0], coord[i][1]),
                map: GoogleMap,
                title: 'Hello World!'
            });
}


        }else{
            alert(data.error.message);
        }
    },
    error: function(data){
        console.log(data);
    }

});
}

function initMap() {

var myLatLng = {lat: 43.1107168, lng: 12.3908279};

GoogleMap = new google.maps.Map(document.getElementById('map'), {
    zoom: 2,
    center: myLatLng
});

}

This method is expected to be successful!

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

jquery target descendants with specific names

In the provided HTML code snippet, there is a main div with the class name of cxfeeditem feeditem, and it contains multiple child elements with similar class names and structure. My query pertains to extracting values from specific children within all the ...

issues arise when trying to make an ajax request in rails

As a newcomer to Rails, I'm fumbling my way through some errors. Attempting to execute an ajax call using link_to and respond to a js.erb template has proven to be quite the challenge for me. The link appears as intended: <a href="/show" data-meth ...

What is the mechanism behind ajax operation on a wame server?

Hello everyone, I'm diving into learning AJAX for the first time by following tutorials on w3schools. Despite my best efforts to follow the step-by-step instructions, I am struggling to make an AJAX example work. Could someone please assist me? Thank ...

What are some tips for incorporating Google Maps v3 with Twitter Bootstrap?

I'm looking to incorporate Twitter Bootstrap's Tabbed Menus into a Google Maps project that is currently coded entirely in javascript. The issue I'm facing is that since Twitter relies on jQuery, I'm unsure of how to effectively utilize ...

Troubleshooting Query Param Problems in EmberJS Route Navigation

("ember-cli": "2.2.0-beta.6") A search page on my website allows users to look for two different types of records: Users or Organizations. The URL for this search page is /search and I have implemented query parameters to maintain the state and enable ba ...

Personalizing File Selection

What is the process for customizing file uploads? <%= f.file_field :image, class: 'inputfile' %> <label for="image">Choose an image</label> I am looking to replace "choose an image" with "choose a file" ...

JavaScript Filtering JSON Data Based on Date Range

I am attempting to filter a basic JSON file based on a specified date range, with both a start date and an end date. Below is the function I have created for this task: var startDate = new Date("2013-3-25"); var endDate = new Date("2017-3-2 ...

Transform them into async/await in JavaScript

Exploring the promise-retry library, I discovered the following syntax: promiseRetry(function (retry, number) { return doSomething() .catch(retry); }) .then(function (value) { // .. }, function (err) { // .. }); Since I am utilizing a ...

Can CSS actually generate accurate inches?

Can you accurately set the width of an element, like a div, in inches and expect it to maintain that width across different devices? Or will it simply scale at a ratio like 1in = 96px? Edit: Try using CSS to set an element's width in inches and then ...

"Retrieve the values of the items that have been chosen from a list using jQuery

In my PHP page, I have a list displayed using the following script: <div id='demo' style="padding-left:20px"> <select name='lists[]' multiple='multiple' class='multiselect' > <?php $sql="select list ...

Tips for maintaining consistency between server-side Java and client-side JS DTO properties

Greetings, I am in search of a solution or plugin within Eclipse that can ensure synchronization between server-side Java DTO properties and their corresponding client-side JSON elements as the codebase evolves. For instance, in a web application with a Ja ...

"The error message "Node JS, MYSQL connection.query is not a valid method" indicates

db_config.js: const mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'test' }) connection.connect(function(err) ...

Activate the Masterpage menu to emphasize its current state

I am currently utilizing the AdminLTE template on my website. One issue I have encountered is with the menu and its child menus. When redirecting to different pages using image buttons, the menu collapses back to its original state. While navigating throu ...

Disabling the search function when it is clicked (before any actions are taken)

I've recently implemented a search form on my website, where the search field opens up upon clicking the search icon.https://i.stack.imgur.com/UeErx.png To make the search icon clickable, I disabled the search function. var $searchBtn = $search.find ...

Aggregating documents in MongoDB based on specific criteria shared by all members of the group

I'm currently working with a set of example documents structured like this: /* 1 */ { "_id" : ObjectId("61c50482f176d72cb660baa3"), "answer" : "yes",... /* 2 */ { "_id" : ObjectId(&quo ...

Preventing Multiple Form Resubmissions in PHP

I have multiple forms that require navigation from the initial form to the final form. Each form includes both 'NEXT' and 'BACK' buttons for moving forward and backward in the process. I am looking for a way to prevent the confirmation ...

Tips for fixing the "Uncaught TypeError: Cannot access property 'get' of undefined" error in Vue.JS 2

Here is my component: methods: { reloadMessage() { setTimeout(function () { this.$http.get(window.BaseUrl + '/message/inbox'); }, 1500); } } And here are my routes: Route::group(['prefix' => &ap ...

The pagination in React using React Query will only trigger a re-render when the window is in

Currently, I am utilizing React-Query with React and have encountered an issue with pagination. The component only renders when the window gains focus. This behavior is demonstrated in the video link below, The video showcases how the component re-renders ...

Issue with CSS styles not linking correctly to ejs templates

I'm having trouble linking my CSS stylesheet in my project. I have the CSS file stored in a public folder with a css subfolder within it. Despite trying various methods, I can't seem to get the stylesheet to connect properly. Below is a snippet f ...

Adding data from a database into an object in PHP for temporary use during the loading process can be achieved by following

I'm a beginner in PHP and I have some code that retrieves category type data from a database. I want to temporarily store this data in a PHP object while the page is loading. Initially, I need to load all predefined data and then use it when a certain ...