I need some help understanding scope in Javascript. I posted a similar question earlier and prematurely marked it as accepted. (The solution didn't work in my case).
I've got javascript (a) and jQuery script (b). I need to access some values from (a) in (b).
In (a) I've got:
function map_maker_js( args ) {
var map = new google.maps.Map(document.getElementById( args['id'] ), myOptions);
//rest of the code for building the map goes here
google.maps.event.addListener(map, 'tilesloaded', viewport_bounds);
function viewport_bounds() {
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var maxLat = ne.lat();
var maxLong = ne.lng();
var minLat = sw.lat();
var minLong = sw.lng();
var the_maps_bounds = [maxLat, maxLong, minLat, minLong];
//return(the_maps_bounds);
}
}
In jQuery script (b), I need the_maps_bounds, which is calculated by viewport_bounds(). I can't simply move google.maps.event.addListener(map, 'tilesloaded', viewport_bounds); into (b), because 'map' is out of scope. This won't work in (b):
google.maps.event.addListener(map, 'tilesloaded', function() {
// This code will only execute after event `tilesloaded` happens
var the_maps_bounds = viewport_bounds()
// now do something with the bounds
// ...
});
If I move the viewport_bounds() function outside of map_maker_js, then I'll have to add map as an argument, which won't work in (b), either.
The code that I'm working on is in a WordPress plugin. I don't think that that will affect the answer, though.
I'm learning still learning javascript. What's the best way to solve this?
Thank you
Update:
Thank you Rob W for your suggestion. This is what I've got now:
var the_maps_bounds;
function map_maker_js( args ) {
var map = new google.maps.Map(document.getElementById( args['id'] ), myOptions);
//rest of the code for building the map goes here
google.maps.event.addListener(map, 'tilesloaded', viewport_bounds);
function viewport_bounds() {
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var maxLat = ne.lat();
var maxLong = ne.lng();
var minLat = sw.lat();
var minLong = sw.lng();
the_maps_bounds = [maxLat, maxLong, minLat, minLong];
alert(the_maps_bounds); //is the the_map_bounds working
return(the_maps_bounds);
}
}
In script (b), I've got:
jQuery.noConflict();
jQuery(document).ready(function($) { //how jQuery scripts are written in WordPress
alert(window.the_maps_bounds);
//rest of my functions
});
When I view the page, I get "undefined" in the alert box and then, an alert box with the lat longs. I also tried the alert without 'window'. And on the ready event:
$('#map').ready(function() {
alert(the_maps_bounds);
});
I guess that the_maps_bounds in script (b) doesn't have a value for soem reason. Is the alert firing before its value is set in script (a)? Is something else going on? Any ideas? Thank you.