1

I'm trying to retrieve data from JQuery function and pass it into global variables to use with Google Maps. These variables have to stay global, otherwise Google Maps don't work with them. I manage to get all data that I need from AJAX url and it logs perfectly but only inside Jquery function. If I log it outside of it, it's undefined. Is there anyway to pass those values to global variables?

function displayMarkers() {    
    var latlng = new google.maps.LatLng(latitd, longtd);
    var name = titleName;
    createMarker(latlng, name);    
}  

var latitd;
var longtd;
var titleName;       

$(document).ready(function() {
    $('#earthquakes').click(function() {    
        getQuakes();
    });

    function getQuakes() {
        $.ajax({
            url: 'http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=' + yesterDate + '&endtime=' + displayDate,
            success: function(data) {
                console.log(data);
                $.each(data.features, function(key, val) {
                    var coord = val.geometry.coordinates;
                    locationD = {
                        latd: coord[0],
                        lngd: coord[1]
                    };
                    latitd = locationD.latd;
                    longtd = locationD.lngd;
                    titleName = val.properties.title;

                    console.log(latitd, longtd);
                    console.log(titleName);    
                });
            }    
        });    
    }    
});
Nebular Dust
  • 403
  • 1
  • 6
  • 17

2 Answers2

1

Your code should be like this

var latitd;
var longtd;
var titleName;

$(document).ready(function () {
    $('#earthquakes').click(function () {
        getQuakes();
    });
});

function getQuakes() {
    $.ajax({
        url: 'http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=' + yesterDate + '&endtime=' + displayDate,
        success: function (data) {
            console.log(data);
            $.each(data.features, function (key, val) {
                var coord = val.geometry.coordinates;
                locationD = {
                    latd: coord[0],
                    lngd: coord[1]
                };
                latitd = locationD.latd;
                longtd = locationD.lngd;
                titleName = val.properties.title;

                console.log(latitd, longtd);
                console.log(titleName);

                //Call this function to display here after success ajax
                displayMarkers();
            });
        }
    });
}

function displayMarkers() {
    var latlng = new google.maps.LatLng(latitd, longtd);
    var name = titleName;
    createMarker(latlng, name);
}
Parth Trivedi
  • 3,802
  • 1
  • 20
  • 40
-1

Add an async:false to your ajax request.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182