I am new to javascript and want to understand what is going on with my code. I am using jQuery and OpenLayers to do some web mapping.
Here is code example 1, where my map variable is created within the onReady function:
$(document).ready(function(){
var map = new.OpenLayers.Map('map', options);
$.get(my_python.cgi_script which returns an html table of available layers)
});
As far as I understand, my 'map' variable has a local scope.
Within that function I add some layers, generate controls, etc. All working and covered in the OpenLayers documentation. I am also using jQuery's get method to call a python.cgi script which dynamically generates a table of available layers. This all occurs within the above onReady.
I needed to work with the dynamically generated content and found that I needed to place my code into an onLoad function. If I place the second codeblock into an onReady function the thumbnails are not accessible via jQuery because of the order in which things are rendered.
$(document).ready(function(){
var map = new.OpenLayers.Map('map', options);
//More code to dynamically generate a list of available layers, stored in a table
$.get(my_python.cgi_script which returns an html table of available layers)
});
$(body).onLoad(function(){
$(img.thumbnail).bind('click', function(){
var name = $(this).attr('layer_name_id')
var layer = new OpenLayers.WMS(//all the stuff to add the layer, including name)
map.addLayer('layer') //map undefined due to scope
});
});
In the above block 'map' is undefined in the second variable. I understand why (scope) and decided that map needed to be a global variable. I then tried:
var map; //This is a global because it is defined outside of any functions?
$(document).ready(function(){
map = new.OpenLayers.Map('map', options);
//More code to dynamically generate a list of available layers, stored in a table
$.get(my_python.cgi_script which returns an html table of available layers)
});
$(body).onLoad(function(){
$(img.thumbnail).bind('click', function(){
var name = $(this).attr('layer_name_id')
var layer = new OpenLayers.WMS(//all the stuff to add the layer, including name)
map.addLayer('layer')
});
});
The map variable is still undefined. Why? Am I misunderstanding how a global works?
I was able to get everything working by putting the onLoad function inside of the onReady code block. I am not sure why the below is working:
$(document).onReady(function(){
var map = new.OpenLayers.Map('map', options);
//More code to dynamically generate a list of available layers, stored in a table
$.get(my_python.cgi_script which returns an html table of available layers)
$(body).onLoad(function(){
$(img.thumbnail).bind('click', function(){
var name = $(this).attr('layer_name_id')
var layer = new OpenLayers.WMS(//all the stuff to add the layer, including name)
map.addLayer('layer')
});
});
});