Create an OpenLayers map programmatically
Sometimes it is useful to abstract away the repetitive layer creation code with a configuration-based approach.
For example consider this very simple map taken from the OpenLayers examples:
How could we avoid repeating invoking the layer contructor and instead provde a framework that allows us to instantiate any layer with just configuration? The solution is quite simple.
First of all we need to define our configuration structure, which is straightforward to do in javascript:
Note that the constructor, which we call provider, has not yet been dereferenced to the actual function. This is on purpose because in this way we can load the configuration independently of OpenLayers. This can be useful especially when trying to optimize page loading time.
Now all we need is some basic glue to make it all work. Basically a builder function and the a for loop over the configuration array.
For example consider this very simple map taken from the OpenLayers examples:
How could we avoid repeating invoking the layer contructor and instead provde a framework that allows us to instantiate any layer with just configuration? The solution is quite simple.
First of all we need to define our configuration structure, which is straightforward to do in javascript:
Note that the constructor, which we call provider, has not yet been dereferenced to the actual function. This is on purpose because in this way we can load the configuration independently of OpenLayers. This can be useful especially when trying to optimize page loading time.
Now all we need is some basic glue to make it all work. Basically a builder function and the a for loop over the configuration array.