JS objects synchronisation – true story

It looks like I know why I was getting so strange results in my bear with JS and Google Maps API. Well, true reason is something I call programming through C&P, or simply using others code without full understanding (let’s face it – even without a little ;-)) ) since I’ve got copied this function call from Google Maps documentation. Now You know what I mean with C&P style ;-))

Let’s look in code, in showAddress function:

if (geocoder) {
geocoder.getLatLng(
  address,
  function(point) {
     if (!point) {
        alert(address + " not found");
     } else {
         map.setCenter(point);
         out = out + ((++count) +
           " showAddr after setCenter -  lng=" + 
           map.getBounds().getSouthWest().lng()) + "\n";
     }
   }
);
}

My humble debug variable (out) is updated in unnamed function, passed to geocoder.getLatLng as an parameter. This call is asynchronous, and output is added after setCenter is finished. In meantime, the rest of code is run in parallel. The rest – outside of unnamed function. If I would place debug statement after getLatLng call output would be much more coherent and would show that in main code block, right after call getLatLng bounds are not changed – they are changed when asynchronous call is finished. So – no more mystery.

And some more explanations are in this thread. BTW Mike, who has enlightened me is autor of previously mentioned Google Maps events list.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.