0

I'm doing a for loop to check against some values, on here is a short version. What I don't understand is why console.log(indirizzo[a]); is giving undefined while if I do console.log(indirizzo); I get all values

  var indirizzo = [];

  for (var i = 0; i < savedRepods.length; i++) {
    for (var a = 0; a < ids.length; a++) {
      if(savedRepods[i] == ids[a]) {
        var geocoder = new google.maps.Geocoder;
        var latlngStr = coords[a].split(',', 2);
        var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
        geocoder.geocode({'location': latlng}, function(results, status) {
          indirizzo.push(results[0].formatted_address);
        });
        console.log(indirizzo[a]);
      }
    }
  }

result if I do console.log(indirizzo);

0: "Corso Vittorio Emanuele, 1, 09017 Sant'Antioco SU, Italia"
1: "Via Nazionale, 78, 09017 Sant'Antioco SU, Italia"
2: "Via Giosuè Carducci, 15, 09017 Sant'Antioco SU, Italia"
3: "Via Perret, 11, 09017 Sant'Antioco SU, Italia"
4: "Lungomare Amerigo Vespucci, 2A, 09017 Sant'Antioco SU, Italia"

result if I do console.log(indirizzo[a]);

undefined
rob.m
  • 9,843
  • 19
  • 73
  • 162
  • The geocoder is asynchronous – geocodezip Mar 01 '20 at 23:10
  • @geocodezip i see, how would I solve it then? – rob.m Mar 01 '20 at 23:11
  • @geocodezip I'm trying to follow the answer but it's confusing, should I use a setTimeOut? – rob.m Mar 01 '20 at 23:18
  • `setTimeout` is generally a "Bad Idea"© to solve asynchronous issues (you might be able to make it work, but you are either wasting time or will run into intermittent issues). Use the data in the callback function when/where it is available – geocodezip Mar 01 '20 at 23:38
  • @geocodezip i'm really getting confused on the callback, read the docs too. Would you be able to put up an answer? – rob.m Mar 01 '20 at 23:43
  • possible duplicate of [Mapping multiple locations with Google Maps JavaScript API v3 and Geocoding API](https://stackoverflow.com/questions/29463131/mapping-multiple-locations-with-google-maps-javascript-api-v3-and-geocoding-api) – geocodezip Mar 02 '20 at 03:16
  • @geocodezip thanks but got an answer here https://stackoverflow.com/a/60480896/1018804 – rob.m Mar 02 '20 at 22:19

1 Answers1

0

This line here will be adding a + 1 for every id. I assume the id array is longer than 4, which will be longer than the amount of items of indirizzo, thus resulting in undefined

for (var a = 0; a < ids.length; a++) {
Harmenx
  • 938
  • 1
  • 5
  • 13