Skip to content Skip to sidebar Skip to footer

AJAX Call In An Infowindow: Scope Issue

Or at least I believe it's a scope issue, correct me if I'm wrong. I have a for loop that generates markers on my map. Each infowindow loads different content using callbacks to an

Solution 1:

What is happening:

  1. you click on the infowindow
  2. getStationInfo(infoWindowDiv) is called, fires off an AJAX request, but returns nothing useful ("undefined", there is no return statement)
  3. The AJAX function will encounter an error (url "Unnecessary at this point" will not cause the onreadystatechange function to fire). But you tell us that isn't a problem.
  4. The script encounters the javascript error Uncaught TypeError: Cannot call method 'appendChild' of null because the div with id infowindow hasn't been attached to the DOM.

Suggest adding an event listener on the infowindow to not attempt to access the div with id="infowindow" until it has been rendered (domready).

Working code:

    var xhr = "";
    var infowindow = new google.maps.InfoWindow();
    var map = null;
    var marker, i;
    var polylineCoordinates = [new google.maps.LatLng(78.782762, 17.917843),
                               new google.maps.LatLng(-0.829439, -91.112473),
                               new google.maps.LatLng(15.066156, -23.621399)
                              ]


      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(78.782762,17.917843),
          zoom: 10,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
            map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);

    for (i = 0; i < polylineCoordinates.length; i++) {
        marker = new google.maps.Marker({
            position: polylineCoordinates[i],
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent("<div id=\"infowindow\" style=\"height:50px;width:200px;\"></div>");
                infowindow.open(map, marker);
            google.maps.event.addListenerOnce(infowindow,"domready", function(){
                  getStationInfo(infoWindowDiv);
                });
        })(marker, i));

    } //End adding markers loop

    }
            function infoWindowDiv(stationInfo) {
                var add = document.createTextNode(stationInfo);
                document.getElementById("infowindow").appendChild(add);
            }


            function getStationInfo(callback) {
                var stationInfo = "This is a Test";
                callback(stationInfo)
            } //end getStationInfo

    google.maps.event.addDomListener(window, 'load', initialize);

Post a Comment for "AJAX Call In An Infowindow: Scope Issue"