0

Your Google Maps code structure looks something like this:

<script>
function initMap() {

}

var locations = 
[
        {lat: -31.563910, lng: 147.154312},
        {lat: -33.718234, lng: 150.363181}
]
</script>

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=API-key&callback=initMap" >
</script>

The thing is, you want to populate locations via a call to the server (using XMLHttpRequest , i.e. a vanilla JavaScript AJAX call because you don't want to use jQuery).

And you don't want the second script block (the call to the Google Maps API) to execute until locations has successfully been populated. How would you achieve this via any of the following:

  • A Callback ?
  • JavaScript Promises ?
  • Any other method you can think of?

Also, is a semaphore, as suggested here a viable way to do this?

Community
  • 1
  • 1
thanks_in_advance
  • 2,603
  • 6
  • 28
  • 44

1 Answers1

1
function initMap() {
  var xhr= new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     LoadGoogleMaps();
    }
  };
  xhr.open();//<-- Your parameters go here
  xhr.send();
}

function LoadGoogleMaps(){
  // Logic to load maps
}

Standard XHR documentation can be found here: http://www.w3schools.com/xml/ajax_intro.asp

Semaphores are a nice idea in concept but can sometimes be extremely difficult to implement. Typically in javascript it's best practice to use callbacks or promises when possible.

Sgt_zippy
  • 66
  • 5