My goal is to load a map with markers on a website. When I trigger the servlet from JavaScript code outside a function, I successfully retrieve the values (coordinates for marker display). However, when I encapsulate the servlet call within a function and then create the map, I encounter an issue where the map appears blank without any visible places or markers. It seems like a completely empty map because even though it loads, all I can see is a mouse pointer resembling a hand as in Google Maps.
The problem lies in the fact that while the map gets loaded, the function responsible for calling the servlet to fetch coordinates does not get executed. This contrasts with the scenario where I place the servlet call directly outside of a function, in which case it works properly. To debug, I utilize the console.log()
method to display the array of values fetched from the servlet, but I only see an empty array: []
.
I suspect that the issue may lie with the xhr.open()
method not being invoked. Admittedly, my experience with JavaScript is limited to just a few days, so I'm uncertain about how to troubleshoot this problem. Any assistance would be greatly appreciated.
function initMap() {
xhr = new XMLHttpRequest();
getLocation(xhr); // calling the function that retrieves location data from the servlet
var bounds = new google.maps.LatLngBounds();
var mapDiv = document.getElementById('map');
map = new google.maps.Map(mapDiv);
map.setCenter(new google.maps.LatLng(latArray[0], lngArray[0]));
map.setZoom(18);
console.log(deviceId);
console.log(latArray);
latArray.forEach(function(lat, i) {
var infoWindow = new google.maps.InfoWindow({
content: '<div id="content">' + '<p style="color:#000000">DeviceID:<p>' + '<p>' + deviceId[i] + '</p>' + '</div>'
});
marker = new google.maps.Marker({
map: map,
mapTypeId: google.maps.MapTypeId.ROADMAP,
position: new google.maps.LatLng(latArray[i], lngArray[i]),
icon: "phone6.png"
});
marker.addListener("click", function() {
placeMarker(this.map, this.marker, latArray[i], lngArray[i]);
});
});
}
function open() {
xhr.open('POST', 'GetLocationFromDB', true);
xhr.send();
}
function getLocation(xhr) {
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
data = JSON.parse(xhr.responseText);
for (i = 0; i < data.length; i++) {
if (!((i + 1) % 3 == 0)) {
latArray.push(data[i]);
lngArray.push(data[i + 1]);
i = i + 2;
deviceId.push(data[deviceIdLoopCount]);
deviceIdLoopCount += 3;
}
}
}
}
}
Edit:
Upon further research, I discovered that you cannot directly call the xhr.onreadystatechange
function itself – instead, it's more of a reference. Despite attempting to execute onreadystatechange()
, I found it unsuccessful. As a workaround, I passed xhr.onreadystatechange
to a variable before invoking the function. How should I proceed in executing it correctly?