JS global variable not being set on first iteration

后端 未结 3 1025
猫巷女王i
猫巷女王i 2020-12-20 04:34

I\'m trying to give a global variable a value after some code is processed. It\'s not working as planned.

What I do is enter an address and city in two textboxes. It

3条回答
  •  感动是毒
    2020-12-20 05:08

    Google geocoding service makes an AJAX call which is asynchronous. When you call codeAddess() it fires the AJAX request and immediately returns. The response has not been received yet so your variable has not been set but you try to get it with getLatLng() anyway which shows up an empty alert box (I suppose). What you want to do is pass a callback to the geocoding function and do your subsequent work there. For example,

    function codeAddress(fn) {
       /* Code here */
       if (status == google.maps.GeocoderStatus.OK){
         /* More code here */
         /* Call callback in the end or after setting*/
         fn();
      }
    }
    

    You can set it up like this:

    $("#locationadd").click(function() {
       codeAddress(getLatLng);
    });
    

提交回复
热议问题