Synchronization between objects in JavaScript

I’m working on some Google Maps mashup and I’ve ran on weired problem. I want to display map, then let user do search for some place, redraw map, and with AJAX call check if on freshly redraw map is something to mark. Of course I need to pass bounds (map.getBounds()) to this call. So I have function called showAddress in some external file, and embedded in HTML code (onClick) calls to showAddress, then I gets new bounds, and send it via AJAX to server to check if there are some interesting points to add to map (as overlay).

But this fails. After call to showAddress bounds are not changed (map is redrawn, but map.getBounds returns old values! I’ve added some delay (setTimer) and voila! it started to work. But delay had to be around 1 second to work in almost every case. So I started stripping code down, and finally got something like this:

  • create map
  • let user to search for new place
  • in onClick pass to debug global counter and bound longitude next increment counter
  • call for showAddress and pass to debug identical data like earlier
  • again in onClick dump pass data to debug
  • show debug output

From following code I would expect something like:

  1. onClick 1 + longitude from old map
  2. showAddress and longitude from new place
  3. onClick 2 + longitude from new map

But, surprise, surprise! results are different! Points from this list are in real life ordered 1, 3, 2. This explains why my application fails, but why it is happening??? I would say that calls to function should be synchronous – JS interpreter should wait to earlier task finish. But debug output says something different. Weired…

Is this some mystery or I’m doing some obvious (for JS masters) mistake???? Maybe it is related to some internals of GMap2 object, but how I should to get new coordinates for my app?

Want to test it? Go for http://nhw.pl/GMAP/ enter in form some place other than Warsaw (I’m using to tests Berlin) click on Go!. When everything is displayed, examine debug output clicking on Show output. Correlate it with HTML code and JS code.

Join the Conversation

2 Comments

  1. Hi, looks like showAddress is an asynchronous method and possibly has a callback param. You should call map.getBounds after/in callback function.

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.