0

I'm coding something on php with javascript and something really strange is happening.

I have this code:

   var lat = [];
   var lng = [];
    downloadUrl('db.php', function (data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName('marker');
        Array.prototype.forEach.call(markers, function (markerElem) {

          lat.push(markerElem.getAttribute('lat'));
          lng.push(markerElem.getAttribute('lng'));


          var icon = customLabel[type] || {};

          var marker = new google.maps.Marker({
            map: map,
            position: point,
            label: icon.label
          });      
        });
      });

When I run console.log(lat) or lng I see that the array contains some entries (9 to be exact) but then I print console.log(lat.length) and it sais that the length is 0.

But then if under that code I add some more entries manuallylat.push("new entry"); I see that is added to the previous content and the length changes to 1.....What is going on here? On the picture you can see after I added the new entry, the length sais that is 10 there, but the console reports 1. Any ideas?

enter image description here

------EDIT----

function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: new google.maps.LatLng(47.401775, 8.772933),
        zoom: 5
      });

      var infoWindow = new google.maps.InfoWindow;
      // Change this depending on the name of your PHP or XML file



      var lat = [];
      var lng = [];


      downloadUrl('db.php', function (data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName('marker');
        Array.prototype.forEach.call(markers, function (markerElem) {
          var id = markerElem.getAttribute('id');
          var name = markerElem.getAttribute('name');
          var address = markerElem.getAttribute('address');
          var type = markerElem.getAttribute('type');
          lat.push(markerElem.getAttribute('lat'));
          lng.push(markerElem.getAttribute('lng'));


          var infowincontent = document.createElement('div');
          var strong = document.createElement('strong');
          strong.textContent = name
          infowincontent.appendChild(strong);
          infowincontent.appendChild(document.createElement('br'));
          var text = document.createElement('text');
          text.textContent = address
          infowincontent.appendChild(text);

          var icon = customLabel[type] || {};

          var marker = new google.maps.Marker({
            map: map,
            position: point,
            label: icon.label
          });

          marker.addListener('click', function () {
            infoWindow.setContent(infowincontent);
            infoWindow.open(map, marker);
          });
        });
      });

      lat.push("new entry");

      console.log(lat);

}
Capie
  • 976
  • 1
  • 8
  • 20
  • 1
    Can you show the response coming from server side? Like, the plain response – Phiter Aug 30 '18 at 11:19
  • Can you show us the `downloadUrl` function? Since this is probably asynchronous, you can't expect the array to be filled right away – Luca Kiebel Aug 30 '18 at 11:19
  • 1
    I suspect it is a scope issue, and when you are asking for the length at the console, you are not in the same scope as your variables. – Dragonthoughts Aug 30 '18 at 11:20
  • Please edit your code to show where you are putting the console logs in – Dominic Aug 30 '18 at 11:21
  • the `downloadUrl` is taken from google developers site, im trying to code something with maps. The scope....I declare the function out of the `downloadUrl` (where it gets filled) and I ask for the length after the downloadUrl finished. The thing is that i can't also access the elements on the array even if the console shows that there's something inside. – Capie Aug 30 '18 at 11:22
  • Your problem most likely isn't inside the code you showed us. Please debug and specify the position where the problem occurs. – Ahorn Aug 30 '18 at 11:25
  • XMLHttpRequest is asynchronous. You are logging before request has completed. It's like trying to eat a pizza before it gets delivered. Note that the console shows live objects...not snapshots – charlietfl Aug 30 '18 at 11:34
  • I'm sorry, im new in Js, but isnt it like this that if i store some content on a variable, this content will remain and will be accessible within the same scope? – Capie Aug 30 '18 at 11:46

1 Answers1

1

This is common with asynchronous operations. The little warning i in the browser next to your array, indicates that the contents of the array have just been evaluated. The browser console lazily evaluates the array when it is expanded.

In the other hand, when you use:

console.log(array.length)

the length is printed exactly as it was at the time the instruction was executed.

If you want to get exact contents of your array without the browser's evaluation magic, use:

console.log(JSON.stringify(array))

Your code should work after the following changes:

function initMap() {

    downloadUrl('db.php', function (data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName('marker');
        Array.prototype.forEach.call(markers, function (markerElem) {
            var id = markerElem.getAttribute('id');
            var name = markerElem.getAttribute('name');
            var address = markerElem.getAttribute('address');
            var type = markerElem.getAttribute('type');
            lat.push(markerElem.getAttribute('lat'));
            lng.push(markerElem.getAttribute('lng'));


            var infowincontent = document.createElement('div');
            var strong = document.createElement('strong');
            strong.textContent = name
            infowincontent.appendChild(strong);
            infowincontent.appendChild(document.createElement('br'));
            var text = document.createElement('text');
            text.textContent = address
            infowincontent.appendChild(text);

            var icon = customLabel[type] || {};

            var marker = new google.maps.Marker({
                map: map,
                position: point,
                label: icon.label
            });

            marker.addListener('click', function () {
                infoWindow.setContent(infowincontent);
                infoWindow.open(map, marker);
            });
        });
        //log the array here
        console.log(lat);
    });

}
Osvaldo Maria
  • 340
  • 5
  • 14