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;
    }));
}
3
  • 2
    Well you have another issue treating an asynchronous request as synchronous. You really need to rethink your code. Commented Feb 25, 2020 at 18:47
  • 1
    stackoverflow.com/questions/14220321/… Commented Feb 25, 2020 at 18:48
  • @epascarello, i am trying to rethink what i wrote and looking at the link you provided Commented Feb 25, 2020 at 19:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I removed the true from the open, and get an error on this results.push(result.results[0].geometry.location); geometry is undefined
Check the response of the api call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.