0

I'm struggling to get a grip of how to access the result of initMap() outside of the function, so I can pass it to my endResultofJSON() function. This, as the initMap() function gets the result based on an eventlistener. Even after triggering the eventlistener, it seems the result of it isn't accessible. I tried adding window.json_final; right before the return line to store it in the window, though I cannot access the result after anyways in between the triggering of the event..

..so my endResultofJSON() function of course triggers the else-condition.


function initMap() {
  let input = document.getElementById("searchMapInput");

  let autocomplete = new google.maps.places.Autocomplete(input);

  autocomplete.addListener("place_changed", function() {
    let place = autocomplete.getPlace();


    let latitude = place.geometry.location.lat();
    let longitude = place.geometry.location.lng();
    let latlon = `${latitude},${longitude}`;
    let usertime = getUsertimelol();
    let API_KEY = "myapikeyhere";
    var json_final = `https://maps.googleapis.com/maps/api/timezone/json?location=${latlon}&timestamp=${usertime}&key=${API_KEY}`; // ? Can be used after a search to retrieve the JSON outside of this function. Until new search is done, this variable holds the old value, which is valuable in itself.
    console.log(json_final);
    return json_final;
  });
}

function endResultofJSON() {
  var xhr = new XMLHttpRequest();

  xhr.open("GET", initMap(), true);
  xhr.onload = function() {
    if (xhr.status === 200) {
      var output = JSON.parse(xhr.responseText);
      console.log(output.status);
      window.output.rawOffset;
      window.output.dstOffset;
      console.log(output.rawOffset);
      console.log(output.rawOffset);

    } else {
      alert("Failed with status of " + xhr.status);
    }
  };
  xhr.send();
}
  • 1
    Have `initMap` call `endResultofJSON` with the URL? – CertainPerformance Oct 05 '19 at 12:59
  • 1
    Your `initMap()` function has no "result". There's no `return` statement. The `return` statement inside that event listener function won't do anything. – Pointy Oct 05 '19 at 13:03
  • @Pointy, ahh "The return statement stops the execution of a function and returns a value from that function." - there is no result of the function. I get it. – Streching my competence Oct 05 '19 at 13:08
  • @CertainPerformance then I have to put `endResultofJSON()` before the `initMap()` function, but that won't work since `initMap()' generates the URL.. Do you have a suggestion on how to get around that? – Streching my competence Oct 05 '19 at 13:10
  • `endResultOfJSON()` should take the URL as a parameter. You can then call it from inside the event listener function and pass in the URL it creates. – Pointy Oct 05 '19 at 13:14

0 Answers0