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.