Defining new Cesium.ProviderViewModel with url from String array

Cesium version 1.21

I am reading json from a file and extracting URLs to add as ProviderViewModels in the baseLayerPicker. Currently, the creationFunction is executed only after the user selects that layer. At that point, I cannot get the layer that they have chosen to retrieve the URL. Below is the code

int i = 0;

for(i = 0; i < jsonImageServers.length; i++){

imageryViewModels.push(new Cesium.ProviderViewModel({

name : jsonImageServers[i].name,

tooltip : jsonImageServers[i].tooltip,

iconUrl : Cesium.buildModuleUrl(‘Widgets/Images/ImageryProviders/img.png’),

creationFunction : function() {

return new Cesium.ArcGisMapServerImageryProvider({

url: jsonImageServers[i].url,

enablePickFeatures: false,

ellipsoid: Cesium.Ellipsoid.WGS84





This code breaking on the highlighted line inside the creationFunction after the user selects a layer from the picker. At that point, ‘i’ is not the correct value and I cannot retrieve the correct URL from the array. Anyone ever run into this issue? I cannot have a user go into the Javascript code to hard code their imagery server URLs.

This is a classic JavaScript closure error, and not related to Cesium - all functions refer to the same i variable, not the value of i at the time the function is created.

This might help:

Thanks for the link Scott, I had not run into this before. Was able to fix my code using the link.