Lab4 View and Data API Web Intro JS

(This is a continuation from the previous post: Lab3 “View and Data API Web Intro”)

Now that we have a model uploaded to the A360 storage, the final piece of API functionality that we want to add to our Intro Labs app is an ability to view the uploaded model. To do this, View and Data API provides a client side JavaScript API.

If you look at the Quick Start guide, you can see there are a little bit of coding required for this portion. With very little explanation of what each line of code does (or at least I haven’t seen any), however, it may not be so obvious what the code is doing. In this post, I will try to take a look in more detail. Hopefully it will help understand if you are new to the API.

JavaScript API Layer

There are two JavaScript (.js) files that we are going to use:

  • viewer3D.min.js
  • viewer-embed.js

Let’s take a look at them one by one.

 

viewer3D.min.js

This is the viewer3D library that Autodesk provides. You can find the latest viewer3D from the hosted location:

https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.min.js or

https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.js

viewer3D.min.js is the version without any formatting, while viewer3D.js is human-eyes friendly version.

To use it with our application, we include it in HTML with <script/> tag in the <head/> section. e.g.,

<!– Autodesk Viewer –>
<link rel=”stylesheet” href=”https://developer.api.autodesk.com/viewingservice/v1/viewers/style.css” type=”text/css”/>
<script src=”https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.min.js”></script>

where we included the style sheet css file.

Typically, we use this file as provided. Since it is open source, it is also possible to modify for your needs. You can download from the location mentioned above.

 

viewer-embed.js

This is the portion of the code based from the Quick Start guide, which  I have re-structured as an “utility” for our minimum project. It assumes for a display of a single 3D model with basic UI turned on.  The code looks like below:

viewer-embed.js

var ViewerEmbed = {
    
    // Initialize the viewer, which includes setting a callback function
    // to load the model on success.
    // Arguments:
    // 1) getToken – callback function to get a valid token
    // 2) docUrn – urn of a uploaded model
    // 3) viewerElement – a portion of html document to embed a viewer.
    //
    initialize: function (getToken, docUrn, viewerElement) {
        
        // Options:
        // env is used in to set environment variables. 
        // getAccessToken and refreshToken are called from
        // Autodesk.Viewing.Initializer to get valid access token
         
        var options = {  
            ‘env’: ‘AutodeskProduction’,
            ‘getAccessToken’: getToken,
            ‘refreshToken’: getToken,
        };

        // Create a viewer with basic default set of UI.    
        var viewer = new Autodesk.Viewing.Private.GuiViewer3D(viewerElement, {
            extensions: [‘BasicExtension’]
        });

        // Initialize the viewer with the options.
        // Set the callback to actually load a model for viewing.
        Autodesk.Viewing.Initializer(options, function () { // onSuccessCallback
            viewer.initialize();
            ViewerEmbed.loadDocument(viewer, docUrn); // defined below.
        });
    },

    // Load a document with a given id (=urn) in the viewer.

    loadDocument: function (viewer, documentId) {

        // Find the first 3d geometry and load it.
        Autodesk.Viewing.Document.load(documentId, // arg1: urn
            function (doc) { // arg2: onLoadCallback
                var geometryItems = [];
                geometryItems = Autodesk.Viewing.Document.getSubItemsWithProperties(
                    doc.getRootItem(), // item – document node to begin searching from 
                    { // properties to search for
                        ‘type’: ‘geometry’, // geometry/view/resource/folder/, etc.
                        ‘role’: ‘3d’  // 2d/3d/thumbnail/, etc.   
                    },
                    true); // recursive searcn, true/false

                if (geometryItems.length > 0) {
                    // Finally, load the model
                    viewer.load(doc.getViewablePath(geometryItems[0]));
                }
            },
            function (errorMsg) { // arg3: onErrorCallback
                alert(“Load Error: “ + errorMsg);
            }
        );
    }
}

The above code defines two functions: initialize() and loadDocument(). initialize() takes three arguments: 1) the name of a callback function to get a valid access token, 2) urn of an uploaded model, and 3) a html element to embed a viewer. Actual loading happens in the callback defined in loadDocument(). I have added comments about what each line of code does above.

Notice there are two levels of nested callbacks between them. In the first function, initialize, Autodesk.Viewing.Initializer takes a callback as the second argument, which calls the second function loadDocument. And in loadDocument, Autodesk.Viewing.Document.load takes another callback as the second argument, where finally the viewer loads the targeted model.

We can include this file to your HTML page, e.g.,

  <script src=”Scripts/viewer-embed.js”></script>

(Note: in our exercise, we place the JavaScript files under Scripts folder.)

Later on, when you are ready to explore more features, such as displaying 2D drawing, you can come back to this file and modify for your needs. For now, let’s move on and call this function from your  web form.

 

Embedding the Viewer in a Web Form

In the <head/> section of your web page, include script files we have discussed above, for example:

        <!– Autodesk Viewer –>
        <link rel=”stylesheet” href=”https://developer.api.autodesk.com/viewingservice/v1/viewers/style.css” type=”text/css”/>
        <script src=”https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.min.js”></script>
        <!– ViewDataAPI Intro Code –>
        <script src=”Scripts/viewer-embed.js”></script>

Add the following scrip to initialize the viewer and load a model:

initialize(), getToken()

        <script>
           
            // Initialize the viewer, which includes setting a callback
            // function to load the model.
            // Arguments to ViewerEmbed.initialize:
            // 1) getToken – callback function to get a valid token
            // 2) docUrn – urn of a uploaded model
            // 3) viewerElement – a portion of html document to embed a viewer.
            function initialize() {
                var docUrn = document.getElementById(“TextBoxUrn”).value;
                var viewerElement = document.getElementById(‘viewer’);
                ViewerEmbed.initialize(getToken, docUrn, viewerElement);
            }

            // Returns a valid access token. For our getting started project,
            // we simply return the value of token text box.
            // This will be called from options in Autodesk.Viewing.Initializer:   
            function getToken() {
                var authToken = document.getElementById(“TextBoxToken”).value;
                return authToken;
            }

        </script>

where initialize() calls ViewerEmbed.initialize() which we defined in viewer-embed.js. The first argument, getToken, is the callback function which will be called from Autodesk.Viewing.Initializer to get a valid access token.  In our intro project, we simply get necessary values from the text boxes on the web page that we have defined in the previous labs.

Add a section to embed the viewer, and name it “viewer”. Add a button that trigger the above viewing function, initialize, for example:

    <!– Viewer portion –>
    <input id=”ButtonView” type=”button” value=”View” onclick=”initialize()/><br/>
    … 

    <div id=”viewer” style=”position:absolute; width:97%; height:40%;“></div>

 

An example of final web page might look like this:

2015_0312_Lab4ViewDataAPIWebIntroJS_UI

Tips:  The REST call to register a model for viewing will return the status OK. But the actual process may be still in progress. You may want to add a call to check status. Or you can use the step 12 of LMV Quick Start for testing. Once again, our labs code is the minimum necessary for the viewing. To give you an idea how long it takes, with my environment, rst_basic_sample_project.rvt (which comes with Revit install, 6.44 MB of size) takes about 3 min. rac_advanced_sample_project.rvt (13.4 MB) takes about 10 min. 

Troubleshoot: When the model is not ready, Load Error 9 will be returned. If this happens, wait a little bit, and try again. If you see Load Error 4, a problem might be with getting valid access token. Make sure getToken callback function is defined correctly, and not as within a local scope, for example.

You can download the View and Data API Intro Labs code from here.

 

This concludes the first tour of View and Data API Intro Labs. I hope you will find it helpful to get started with the View and Data API.

Mikako

Update 7/11/2015 : In response to the request I received, I’ve added one more lab’s exercise showing how to access and search objects properties using the viewer API. Please take a look at this post if you are interested in continuing with the tutorial:
Lab5 View and Data API Intro – Get Properties & Search

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s