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

Retrieve the chosen selection from a dropdown menu using AngularJS and Ionic

I've been encountering some issues with the select feature in AngularJS. Despite searching extensively for solutions, none seem to be working for me. The JSON structure I'm dealing with is generated from my service.php: [ { "Name": ...

Tips for successfully installing a package through npm

Looking to set up nest.js Using the guide provided below. https://www.npmjs.com/package/@nestjs/cli Attempted the following command $ npm install -g @nestjs/cli Encountered this error message. bash: /usr/local/bin/npm: No such file or directory Any ...

Troubleshooting Forms Authentication problem in ASP.NET ASHX 302 error situation

I've been working on an ASP.NET application using .NET Framework 4.7.2. In this app, there is a modal pop-up that allows users to enter notes and save them. However, sometimes users encounter issues when their authentication expires during the postbac ...

Issues encountered with registration form functionality (PHP/MySQL)

My form validation and database update seem to have hit a snag. The issue is that the signup() function isn't being triggered when clicking on the "Sign me up" button in home.php (located in the public directory) which links to signup.php (../signup.p ...

Using Angular 4: Redirecting Menu to Component with Electron

I am currently working on my first project using Angular 4 and Electron to develop a desktop application. One of the challenges I'm facing is figuring out how to redirect to a specific component when a submenu item is clicked after overriding the ele ...

Using AJAX and C# to upload images

I'm currently exploring options for uploading an image to a web server without the need to submit a form. After some consideration, I've decided to use Ajax for this task. However, I am having difficulty finding clear examples of how to implement ...

What are the steps to effectively implement the useEffect hook in React?

I'm facing an issue where I am trying to return a function that utilizes useEffect from a custom usehook, but I keep getting the error "useEffect is called in a function which is neither a react function component nor a custom hook." Here's what ...

When using multiple select tags with *ngFor in Angular, modifying the value of the first select tag will have an

<table id="DataTable" border="1" ALIGN="center"> <tr ALIGN="center"> <th>name</th> <th>address</th> <th>number</th> <th>type</th> </tr> <tr class="tcat" *ngFor ...

Is it possible for jQuery to create a popup window displaying a specific value?

Using JavaScript, I have implemented functionality to open a child window when the user clicks on a button from the parent window. The child window contains a textbox and a button. When the user clicks on the button in the child window, I want to retrieve ...

Using sprintf in PHP with the GET method to insert data into an SQL database record

I am currently utilizing Google Maps to extract marker data for inclusion in a form submission. The marker details are stored in MySQL using the following query: // Accessing data from URL parameters $name = $_GET['name']; $address = $_GET[&apos ...

Using JavaScript for Text Processing on Disk

Currently, I have a set of HTML files that require automated processing such as regex replacements and more complex actions like copying specific text blocks from one file to another. I am considering creating a series of scripts to handle this processing ...

Utilizing jQuery show() and hide() methods for form validation

I created a form to collect user details and attempted to validate it using the jQuery hide and show method. However, I seem to be making a mistake as the required functionality is not working correctly. What am I missing? I have searched for solutions on ...

CF component not able to accept arguments when invoked by JavaScript through cfajaxproxy

Ever since updating to ColdFusion 2016 Update 4, I've been experiencing a new issue. Here's the code snippet: <input type='button' name='btn' value='Click me' onclick='proxyFunc();'> Incorporating ...

Synchronous execution following a Node.js for loop integrated with callbacks

I'm facing a dilemma in my Nodejs application involving a for loop with callback functions. The loop iterates over an array, and for each value, an update operation is performed using a query, replacing the current value with the result of the query. ...

Acquire the current audio video stream directly from the web browser

Currently, I am utilizing a JavaScript library that internally invokes getUserMedia. My objective is to access the stream object that has already been initiated. Unfortunately, the library does not provide any means to retrieve it. Is there a method avai ...

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...

Save all user information annually from the date they first sign up

Greetings! I am facing an issue where every time a year is added, it gets inserted between the day and month in the date of entry for a user at our company. var yearOnCompany = moment(user.fecha_ingreso_empresa, "YYYYMMDD").fromNow(); var dateStart = mome ...

Unable to retrieve the image

When trying to fetch an image, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) TopBar.jsx import { useContext } from "react"; import { Link } from "react-router-dom"; ...

Angular 2 Mixup: Using Leaflet and Google Maps with Incorrect Tile Order

I am encountering an issue while working on Leaflet and Google within Angular 2. The problem lies in the Tilemill tiles not rendering properly as they are displaying in a strange order. Here is a screenshot of the current state: https://i.stack.imgur.com/ ...

Is it necessary to have both index.js and Component.js files for a single component in React?

Continuously analyzing various projects, I often come across authors who organize their file structures in ways that are perplexing to me without proper explanation. Take, for instance, a component where there is a folder named Header. Inside this folder, ...