0

When the form is submitted the function buttonClicked() is run. This function runs callGeoCode() which gets the latitude and longitude information for whatever the user typed in the form. Whenever I click the button to submit the form the page reloads. However when I comment out the console.log(location.lat+','+location.lng); line the page doesn't reload. Why would this be? I can't seem to figure it out.

$('#find-location').submit(function () {
     buttonClicked();
     return false;
});    
function buttonClicked() {
    userInput = document.getElementById("locationInput").value;
    var location = callGeoCode(userInput);
    console.log(location.lat+','+location.lng);
}
function callGeoCode(userInput) {
    $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + userInput + '&key=APIKEY-GOES-HERE', 
        function(data) {
            if (data.status === 'OK') {
                var lat = data.results[0].geometry.location.lat;
                var lng = data.results[0].geometry.location.lng;
                return {lat: lat, lng: lng};
            } else {
                return 'FAILED';
            }
        }
    );
}
  • Aside: you can't do `var location = callGeoCode(userInput);` because callGeoCode returns nothing. Similarly, `return {lat: lat, lng: lng};` will fail because the callback function is not providing a return value to any of your code. You should populate your structure with the data from the ajax call inside the ajax callback func. – James Jun 05 '17 at 22:03
  • @James So, how would I be able to callGeoCode return a value? – Backup Boss Jun 05 '17 at 22:10
  • You can't, using async functions does not lead well to returning values. The callback function is the right place to "do things" with the received data, perhaps call another function there and pass it the data you received. Check out [this question](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – James Jun 05 '17 at 22:16
  • @James Thank you so much. – Backup Boss Jun 05 '17 at 22:42

1 Answers1

0

Try this:-

$('#find-location').submit(function (event) {
     event.preventDefault();
     buttonClicked();
     return false;
});   

For geocode api you can try something like

function buttonClicked() {
    userInput = document.getElementById("locationInput").value;
    var locationPromise = callGeoCode(userInput);
    locationPromise.done(function( data ) {
        console.log(data);
        if (data.status === 'OK') {
            var lat = data.results[0].geometry.location.lat;
            var lng = data.results[0].geometry.location.lng;
            console.log("lat:" + lat + "long:" + long);
        }
    }
}

function callGeoCode(userInput) {
    return $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + userInput + '&key=APIKEY-GOES-HERE'); 
}
VivekN
  • 1,562
  • 11
  • 14