1

I am iterating through an array to send a request to an api to get lat and long coordinates, but am only getting one lat and long coordinate returned and then getting this error

NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load '': Document is already detached.

The code I am using is

function GetEachUsersLatLongCoordinates(zips) {
    return (TryCatch(function () {
        let result;
        let results = [];

        let xmlHttp = new XMLHttpRequest();

        for (let i = 0; i < zips.length; i++) {
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    result = JSON.parse(xmlHttp.response);
                    results.push(result.results[0].geometry.location);
                }
            }
            xmlHttp.open("GET", "https://maps.googleapis.com/maps/api/geocode/json?address=" + parseInt(zips[i]) + "&key=" + GoogleAPIKEY + "", true);
            xmlHttp.send(null);            
        }        

        return results;
    }));
}
Chris
  • 2,953
  • 10
  • 48
  • 118

1 Answers1

0

Place the:

let xmlHttp = new XMLHttpRequest();

Inside the loop.

And you can't return the result there as it's run async. You could pass a callback to GetEachUsersLatLongCoordinates or return a promise instead.

Buddy Christ
  • 1,364
  • 8
  • 22