0

Situation

I am calling an API using $.getJSON and would like to set some global variables. I followed this example here and successfully ran the callback function. When I console.log the global variables I want, woodmontTotal and woodmontAvailable, I can see them if run console.log within the callback function. However, outside of the callback function, the global variables are undefined.

My understanding is that to define global variables using values from $.getJSON that the callback function would set the global variables.

My end goal is to show the variables woodmontTotal and WoodmontAvailable in info windows on the map.

Question

  1. How can I set the global variable woodmontTotal equal to object[i].total_spaces where object[i].facilitynumber = "GAR 57'?
  2. How can I set the variable woodmontAvailable to object[i].space_count where object[i].facilitynumber = "GAR 57'?
  3. In the example above, why did that solve the problem whereas my callback function does not set the global variable? What are the differences, if any?

Callback Function

//call the data back
function getGarageCount(callback) {
    var name = "default";
    $.getJSON(url, function(entry) {
        name = entry;
        callback(name);
    });
};
getGarageCount(function(value) {
    $.each(value, function(i, field) {
        if (value[i].facilitynumber === "GAR 31") {
            woodmontTotal = value[i].total_spaces;
            woodmontAvailable = value[i].space_count;
        };
    });
    console.log(woodmontTotal);
    console.log(woodmontAvailable);
});
//set markers
markers = [
    ["4841 Bethesda Avenue (Elm Street)", 38.980724, -77.0964, bethesdaTotal,
        bethesdaAvailable
    ],
    ["7171 Woodmont Avenue", 38.980097, -77.093662, woodmontTotal,
        woodmontAvailable
    ],
    ["921 Wayne Avenue", 38.995740, -77.025652, wayneTotal, wayneAvailable],
    ["801 Ellsworth Drive", 38.997778, -77.025071, ellsworthTotal,
        ellsworthAvailable
    ]
];

Fiddle here.

HTML:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js"></script>
</head>
<body>
    <h1 style="text-align: center;">Parking Garage Availability</h1>

    <div id="map"></div>

    <ul id="list"></ul>
    <p id="GAR57"></p>
    <p id="GAR31"></p>
    <p id="GAR60"></p>
    <p id="GAR61"></p>
</body>

CSS:

#map {
    height: 300px;
    width: 500px;
    margin: 0 auto;
    border: 1px solid black;
}

JavaScript:

var map;
var mapProp;
var marker;
var markers;
var url;
var myData;
var time;
var available;
var total;
var facility;
var position;
var infoWindow;
var bethesdaTotal;
var bethesdaAvailable;
var woodmontTotal;
var woodmontAvailable;
var wayneTotal;
var wayneAvailable;
var ellsworthTotal;
var ellsworthAvailable;

function initialize() {
    mapProp = {
        center: new google.maps.LatLng(38.994890, -77.063416),
        zoom: 9,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"), mapProp);
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            map.setCenter(pos);
        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ? 'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
}
$(document).ready(function() {
    initialize();
    url = 'https://data.montgomerycountymd.gov/resource/qahs-fevu.json';
    $.getJSON(url, function(data) {
        myData = data;
        for (i = 0; i < myData.length; i++) {
            time = (myData[i].asofdatetime).slice(11);
            available = myData[i].space_count;
            total = myData[i].total_spaces;
            facility = myData[i].facilitynumber;
            //get names
            if (facility === "GAR 57") {
                facility = "4841 Bethesda Avenue (Elm Street)";
                $('#GAR57').html('As of ' + time + ' there are ' + available +
                    ' of ' + total + ' at ' + facility);
            } else if (facility === "GAR 31") {
                facility = "7171 Woodmont Avenue";
                $('#GAR31').html('As of ' + time + ' there are ' + available +
                    ' of ' + total + ' at ' + facility);
            } else if (facility === "GAR 60") {
                facility = "921 Wayne Avenue";
                $('#GAR60').html('As of ' + time + ' there are ' + available +
                    ' of ' + total + ' at ' + facility);
            } else {
                facility = "801 Ellsworth Drive";
                $('#GAR61').html('As of ' + time + ' there are ' + available +
                    ' of ' + total + ' at ' + facility);
            }
        }
    });
    //call the data back
    function getGarageCount(callback) {
        var name = "default";
        $.getJSON(url, function(entry) {
            name = entry;
            callback(name);
        });
    };
    getGarageCount(function(value) {
        $.each(value, function(i, field) {
            if (value[i].facilitynumber === "GAR 31") {
                woodmontTotal = value[i].total_spaces;
                woodmontAvailable = value[i].space_count;
            };
        });
        console.log(woodmontTotal);
        console.log(woodmontAvailable);
    });
    //set markers
    markers = [
        ["4841 Bethesda Avenue (Elm Street)", 38.980724, -77.0964, bethesdaTotal,
            bethesdaAvailable
        ],
        ["7171 Woodmont Avenue", 38.980097, -77.093662, woodmontTotal,
            woodmontAvailable
        ],
        ["921 Wayne Avenue", 38.995740, -77.025652, wayneTotal, wayneAvailable],
        ["801 Ellsworth Drive", 38.997778, -77.025071, ellsworthTotal,
            ellsworthAvailable
        ]
    ];
    console.log(markers)
    infoWindow = new google.maps.InfoWindow();
    for (var i = 0; i < markers.length; i++) {
        position = new google.maps.LatLng(markers[i][1], markers[i][2]);
        marker = new google.maps.Marker({
            position: position,
            animation: google.maps.Animation.DROP,
            map: map,
            title: markers[i][0]
        });
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infoWindow.setContent("<div>" + markers[i][0] + "</div>");
                infoWindow.open(map, this);
            };
        })(marker, i));
    };
});
Community
  • 1
  • 1
adin
  • 783
  • 3
  • 13
  • 27
  • Your code _"outside of the callback function"_ runs before `getJSON` can execute the callback. – Cerbrus Nov 19 '15 at 14:07
  • @Cerbrus How do I set it to execute after `getJSON`? I'm not sure how to apply either the example or other threads to my code. – adin Nov 19 '15 at 14:21
  • Move the `});` that's below `console.log(woodmontAvailable);` to the line below `})(marker, i)); };`, so right before the last `});` – Cerbrus Nov 19 '15 at 14:26
  • That worked! Anything I want to happen after the async function runs, I need to wrap my callback function around? – adin Nov 19 '15 at 14:40
  • In the future, can I just do something like `document.ready`, `getJSON`, `callback`, <--much of my code here-->, `end callback`, `end document.ready` ? Would that be bad practice? – adin Nov 19 '15 at 14:45

0 Answers0