JS global variable not being set on first iteration

后端 未结 3 1019
猫巷女王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 04:58

    The problem is geocoder.geocode is asynchronous. You can't do it the way you do because your codeAddress function will return before longlats is set. You need to change your coding style to use longlats only after google maps have returned the result.

    You need to change your code from this:

    $("#locationadd").click(function() {
       codeAddress();
       var get = getLatLng();//value is undefined..
      //i want to do stuff with the values in longlats
    }
    

    To this:

    $("#locationadd").click(function() {
       codeAddress(function(){
         var get = getLatLng();
         //do stuff with the values in longlats
       });
    });
    

    In order to do that, you need to change copyAddress to:

    function codeAddress(callback) {
    
      /*
       * Some stuff
       */
    
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          /*
           * Some stuff
           */
    
          setLatLng(locationsall[counter][1],locationsall[counter][2]);
    
          callback(); // This is where/when the values are returned
                      // so this is where/when we want to execute code.  
        } 
      })
    }
    

    Additional explanation:

    From your comments, it appears that you're still trying to do this:

    var val;
    codeAddress(function(){
        val = getLatLng();
    });
    doStuffWith(val);
    

    This won't work because codeAddress returns BEFORE getLatLng executes. You need to change the style of your coding. You need to write it like this:

    codeAddress(function(){
        val = getLatLng();
        doStuffWith(val);
    });
    

    That is, you need to move all code that you would have written after the call to codeAddress to the function INSIDE codeAddress.

    The reason for it is that the way the code executes is something like this:

    • BROWSER ENTERS JAVASCRIPT PHASE:

         codeAddress is called
                |
                |
                |--------------> inside codeAddress a request to google maps
                |                is made which registers a callback function
                |                to be executed once it returns.
                v
         codeAddress returns
         note that at this point getLatLng isn't called yet
         this is because the browser haven't made the request
         to google maps yet because it's still executing the
         javascript engine.
                |
                v
         code written after codeAddress is executed
         (remember, the call to google maps still haven't happened yet)
                |
                v
         no more javascript to execute
      
    • javascript phase ends, BROWSER ENTERS DOM RENDERING PHASE

         The DOM gets updated and drawn on screen if there are any changes.
      
    • DOM rendering ends, BROWSER ENTERS NETWORK PHASE

         (note: in reality the network layer is asynchronous)
      
         Browser executes pending requests (images, iframes, XMLHttprequest etc.)
         Makes the necessary network connections and begins downloading stuff.
                |
                |
                v
         Browser services completed requests and schedules appropriate events
         (update DOM, trigger onreadystatechange etc.)
         Note that at this point no javascript or DOM updates actually happens.
         The browser does things in a loop, not recursively.
         It is at this point that the google maps request is made.
                |
                v
         No more network operations to service
      
    • network phase ends, BROWSER ENTERS JAVASCRIPT PHASE

         google maps request completes, onreadystatechange executes
                |
                |
                |----> inside onreadystatechange the callback to the
                |      google maps API is called
                |             |
                |             '-----> inside the google maps callback getLatLng
                |                     is called, then the callback to codeAddress
                |                     is called.
                |                          |
                |                          '------> inside the callback to
                |                                   codeAddress you can now
                |                                   use the returned values.
                |                                   This is the reason you need
                |                                   to move all your code here.
                v
         no more javascript to execute
      
    • javascript phase ends, BROWSER ENTERS DOM RENDERING PHASE

    and the event loop continues.

    As you can see, you can't simply return the values from codeAddress. Instead you need to move your code inside codeAddress to have it executed at the right time.

    0 讨论(0)
  • 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);
    });
    
    0 讨论(0)
  • 2020-12-20 05:17

    You get undefined because when calling getLatLng() the value of longlats hasn't been set yet.

    Your function codeAddress() makes an async request, so you need to make it able to accept a callback as an argument.

    codeAddress(function(longLat){
        // do something with longLat
    }); 
    

    When declaring the function codeAddress make sure to execute the callback and pass it the longLat value.

    check this other answer

    0 讨论(0)
提交回复
热议问题