Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have a bigger problem in there. You are calling the asynchronous <a href="http://api.jquery.com/jQuery.ajax/" rel="nofollow noreferrer"><code>$.ajax()</code></a> method, where its callback function will be called after your <code>changeMapLocation()</code> function returns, and therefore your function will not work as you are expecting. Follow the comments in the example below:</p> <pre><code>function changeMapLocation(state) { var lat; var long1; // Since the $.ajax() method is using the asynchronous XMLHttpRequest, it // will not block execution, and will return immediately after it is called, // without waiting for the server to respond. $.ajax({ url: 'url-here', type: 'POST', success: function(longlatJson) { // The code here will be executed only when the server returns // a response to the ajax request. This may happen several // milliseconds after $.ajax() is called. var jsonObj = JSON.parse(JSON.stringify(longlatJson)); lat = jsonObj.results[0].geometry.location.lat; long1 = jsonObj.results[0].geometry.location.lng; // Now lat and long1 are set, but it is too late. Our // changeMapLocation() function will have already returned. } }); // This part will be reached before the server responds to the asynchronous // request above. Therefore the changeMapLocation() function returns an // object with two properties lat1 and lat2 with an undefined value. return {lat1: lat, lat2: long1}; } </code></pre> <p>You should consider refactoring your code in such a way that the logic to handle the ajax response is in the <code>success</code> callback. Example:</p> <pre><code>function changeMapLocation(state) { $.ajax({ url: 'url-here', type: 'POST', success: function(longlatJson) { var jsonObj = JSON.parse(JSON.stringify(longlatJson)); var lat = jsonObj.results[0].geometry.location.lat; var long1 = jsonObj.results[0].geometry.location.lng; // Update your map location in here, or call a helper function that // can handle it: myGoogleMap.setCenter(new google.maps.LatLng(lat, long1)); } }); } </code></pre> <p>Note that <code>changeMapLocation()</code> does not return anything anymore. It will simply change the map location on its own, when the server responds to the Ajax request.</p> <hr> <p>In addition note that your <code>lat</code> and <code>long1</code> variables were enclosed in the scope of the <code>success</code> inner function, and couldn't be accessed from the outer function.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload