I’m seeing a lot of answers on StackOverflow that say that JavaScript executes code sequentially, but I can actually see my own JavaScript not doing so. From the following code:
function centre_map(lat, lng, zoom_level) {
alert('centre_map');
map = new GMap2(document.getElementById('map_canvas'));
var latlng = new GLatLng(lat, lng);
map.setCenter(latlng, zoom_level);
}
function add_markers_within_bounds() {
alert('add_markers_within_bounds');
// add numerous BLUE markers within map bounds using MarkerClusterer
}
function add_marker(lat, lng, place_name, grid, county) {
alert('add_marker');
// add one ordinary RED Google Maps marker
}
centre_map('{{lat}}', '{{lng}}', 12);
add_markers_within_bounds('{{grid}}', '{{place_name}}');
add_marker('{{lat}}', '{{lng}}', '{{place_name}}', '{{grid}}', '{{county}}');
I get the following sequence of events:
- ‘centre_map’ alert
- ‘add_markers_within_bounds’ alert
- ‘add_marker’ alert
- individual RED marker appears on map (i.e. add_marker renders)
- multiple BLUE markers appear on map (i.e. add_markers_within_bounds renders)
Why doesn’t add_markers_within_bounds complete before add_marker gets under way: and how can I make it do so?
I know that one way might be to call add_marker from within add_markers_within_bounds, but for various reasons I’d rather keep it as a separate function.
The Google Maps API sometimes involves sending a request to Google to get the data. If one of these actions involves requesting data, it will be delayed until the HTTP request is complete, and the rest of the code will continue on without it.
It seems to me that
add_markerprobably does not involve requesting data, since you already provide the coordinates, whereasadd_markers_within_boundsmay involve downloading data to know what the coordinates actually are. As such,add_markerwill always happen first, while the data for the other markers is still busy downloading.I’m not sure how the Google Maps API works, but you may be able to specify
add_markeras a callback to occur once all the data foradd_markers_within_boundsis ready.