Search code examples
javascriptcesiumjs

base map selector does not work


I am changing default basemap to mapbox.streets in my code. But it then does not update baselayer from baseLayerPicker widget anymore.

                var viewer = new Cesium.Viewer('cesiumContainer',{
                animation : false,
                homeButton : false,
                baseLayerPicker : true,
                infoBox : true,
                sceneModePicker : true,
                timeline : false,
                navigationInstructionsInitiallyVisible : false,
                navigationHelpButton : false,
                contextOptions: {
                    webgl:{preserveDrawingBuffer:true}
                },
                selectionIndicator : false,
            });
            var layers = viewer.imageryLayers;
            var baseLayer = layers.get(0);
            layers.remove(baseLayer);
            layers.addImageryProvider(new Cesium.MapboxImageryProvider({
                url : 'https://api.mapbox.com/v4/',
                mapId: 'mapbox.streets',
            }));

Am I missing anything? Any help is much appreciated.


Solution

  • In the code you posted, you're swapping out the imagery layer after the viewer (and hence the baseLayerPicker) have already been constructed. What you need to do is make sure the baseLayerPicker is constructed with the correct options up front, to pre-select your intended base layer. The code looks like this:

    var imageryProviders = Cesium.createDefaultImageryProviderViewModels();
    var selectedImageryProviderIndex = 4;  // MapBox Street is 5th in the list.
    
    var viewer = new Cesium.Viewer('cesiumContainer', {
        imageryProviderViewModels: imageryProviders,
        selectedImageryProviderViewModel: imageryProviders[selectedImageryProviderIndex]
    });
    

    When you run this, you'll note that the baseLayerPicker starts with the correct item already selected, and still offers options to swap out to other base layers.