Navbar
  • Introduction
  • Checklists — Planning Cartographer Implementation
  • Functionality Overview
  • Questionnaire Integration
  • Reporting Conversions
  • Custom Scripting and API Usage
  • Initialization Options
  • Launching Recommendation Session
  • API Concepts
  • Overriding Templates
  • Saving Sessions v3
  • API Methods
  • Events
  • Third-Party Analytics Integration
  • Introduction

    Look for code samples on this side of the documentation.

    Welcome to Cartographer!

    Cartographer is a guided recommendation system which uses customer’s catalog data to produce product recommendations based on questions configured by the customer.

    Cartographer can easily connect to product data using the Salesforce Commerce Cloud Open Commerce API. Cartographer’s import functionality automatically retrieves catalog information for categorization, product attribute definition, and product attribute values, which is leveraged to create a guided shopping experience.

    Cartographer provides a basic user experience that can be injected into any eCommerce site with minimal development effort and be used immediately or customized to any degree to meet your design requirements. Retailers can work with the Drive Commerce team to customize the experience for a cohesive experience with the site, or easily customize the templates and use the JavaScript API to create a unique look.

    Checklists — Planning Cartographer Implementation

    Plan Information Architecture

    ☐   Build low fidelity wireframes to determine the desired recommendations flow

    ☐   Identify questions and decide on page grouping

    ☐   Define question types and answers

    ☐   Establish product attributes mapping for each question, and map attribute values to answers

    ☐   Determine product attribute model extensions

    ☐   Decide on attribute extensions mechanism: at the source, in Salesforce Commerce Cloud; or using Cartographer’s extension data.

    ☐   Define product recommendations type

    ☐   Define results segmentation

    ☐   Define supported locales

    Plan Data Import

    ☐   Determine data import method, OCAPI or Excel spreadsheet data source

    ☐   If using OCAPI method, configure OCAPI on staging and production environment

    ☐   Consider creating Cartographer specific OCAPI client id and configuration

    ☐   If using Cartographer Data Augmentation, create related Excel spreadsheet data sources

    ☐   Determine source product catalog categories

    ☐   Determine if image URL transformation is required, and define transformation rules

    ☐   Define product import schedule

    ☐   Configure data sources

    Plan Project Authoring

    ☐   Configure Cartographer recommender project as defined by information architecture section

    ☐   Capture draft and production API keys

    ☐   Publish project

    Plan Front-end Implementation

    ☐   Familiarize with developer documentation: (this document; http://drivecommerce.com/cartographer/developer/)

    ☐   Design recommender experience and build mobile, tablet, and desktop wireframes and high fidelity comps

    ☐   Define interactive elements, including page transitions

    ☐   Decide on supported browser versions and select appropriate integration script loading method

    ☐   Decide on implementation strategy: content asset vs pipelines

    ☐   Implement front-end recommender experience

    ☐   If necessary, deploy Salesforce Commerce Cloud code updates

    ☐   Consider using site preference or another environment specific configuration to store project API key

    Plan Performance and Conversion Tracking

    ☐   Determine analytics integration method: Salesforce Commerce Cloud back-end code or third-party tag manager

    If using Salesforce Commerce Cloud back-end code method:

    ☐   Implement Cartographer tracking tag for add-to-cart action

    ☐   Implement Cartographer tracking tag for checkout confirmation page

    If using tag manager:

    ☐   Determine whether tag manager can be triggered for add-to-cart action and checkout confirmation page

    ☐   Determine whether required product data is available to tag manager events

    ☐   If necessary, update Salesforce Commerce Cloud implementation of tag manager to allow tracking of required events and data

    ☐   Implement tracking tag for add-to-cart action

    ☐   Implement tracking tag for checkout confirmation page

    ☐   Determine IP address ranges to be excluded from analytics tracking

    ☐   Define third-party analytics (Google Analytics, Omniture, etc) tracking requirements

    ☐   Implement third-party analytics integrations

    ☐   Review captured performance and conversion metrics, including conversion time interval

    Plan QA and UAT

    ☐   Validate project API keys on staging and development environments

    ☐   Validate recommender implementation

    Ongoing and Maintenance

    ☐   Review analytics reports

    Functionality Overview

    Conceptually, Cartographer SaaS application is separated into two primary components:

    At the high level, Cartographer tool enables developers and merchandisers to create recommendation experiences by:

    Question Types

    Simple Choice

    Map a single product attribute to a set of predefined answers. Questions can be rendered in the browser experience as distinct push buttons, sliders, dropdowns, or multiple-choice checkboxes.

    Combination (Hybrid) Questions

    Similar to Simple Choice, Combination questions allow you to map multiple products attributes to a single question, exponentially increasing recommendations flexibility.

    Fuzzy Choice

    Simple and Combination choice questions typically produce exact recommendations, determined by whether customer selections match question answers. Fuzzy question allows to make Cartographer algorithm less restrictive, and produce potentially better recommendations. For example, you may configure a question asking for customers preferred colors, with "Black," "Black/Red," "Red," "Red/Blue," "Blue" answer options. If the customer selects "Black/Red" answer, but there are products that may be a better fit (as determined by other questions in the project) with "Black" or "Red" colors, they may be recommended as well, albeit with a lower score.

    Slider

    Allow customers to select the desired value on a numeric scale, rather than a preconfigured answer. Questions of this type would typically map to tangible numeric or physical product attributes, such as price, weight, length, etc.

    Free Text

    Free text questions allow collecting unstructured input from customers, such as names. Values entered in recommender sessions can be retrieved later using Cartographer reports. Free text questions do not affect recommendations engine

    Analytics Tracking

    Cartographer provides some analytics metrics, including a number of overall loads and impressions, as well as segmentation by full or partial conversions. A successful conversion is determined by the following sequence of events:

    To provide accurate reporting, Cartographer internal analytics tools require integration with two storefront events:

    Event tracking may be implemented in many ways, for example by direct modification of Salesforce Commerce Cloud storefront code and templates. Some integration options do not require page code modifications, for example when using a tag manager such as Google Tag Manager (https://tagmanager.google.com) or Tealium. It is also possible to integrate recommendation events collection into third-party analytics tools, such as Google Analytics, Omniture, etc.

    Refer to the developer documentation for specific integration requirements and code samples.

    Maintenance

    Once the initial integration is in place, Cartographer recommender instance can be updated in two ways:

    Questionnaire Integration

    Cartographer provides the hosted JavaScript plugin (https://api.cartographer.drivecommerce.com/api/v3/runtime/client v3) that implements functional flow and responsible for communication with the backend services. Salesforce Commerce Cloud implementation side, in turn, provides elements necessary for skinning the experience, such as HTML templates, CSS, and JavaScript implementing presentation aspects of the experience.

    Commerce Cloud Integration

    Recommender instances may be deployed to Salesforce Commerce Cloud using one of the following options:

    Making Open Commerce API Changes

    Cartographer uses OCAPI to ingest product data and make it available for recommendation builder. While it is generally recommended that a production deployment should use DWRE production OCAPI endpoints to provide the most up-to-date pricing and inventory availability data, staging access may also acceptable given a few conditions:

    Cartographer requires access to the Shop API to retrieve product information, pricing, and availability. Depending on the preferred approach, Cartographer can use existing Client ID or can be provided with a new Client ID.

    If Open Commerce API is already configured and client ID will be reused:

    If Open Commerce API is NOT configured: Please refer to Salesforce Commerce Cloud Open Commerce API documentation for details described in the following steps.

    Script Loading

    Page initialization code (modern browsers)

    
    (function (d, url, c) {
        var script = d.createElement('script');
        script.type = 'text/javascript';
        script.onload = function () { if (c) { c(); } };
        script.src = url;
        d.getElementsByTagName('body')[0].appendChild(script);
    }(document, 'https://api.cartographer.drivecommerce.com/api/v3/runtime/client', function () {
    
        // Script has been loaded and Cartographer is now ready for use.
        var recommender = new Drive.GuidedRecommender({
            // etc.
        });
    
    }));
    
    

    Page initialization code (IE8-compatible)

    
    (function (d, url, c) {
        var script = d.createElement('script');
        script.type = 'text/javascript';
        if (script.addEventListener) {
            script.addEventListener('load', function () { if (c) { c(); } }, false);
        } else if (script.readyState) {
            script.onreadystatechange = function () { if (this.readyState === 'loaded' && c) { c(); } };
        }    
        script.src = url;
        d.getElementsByTagName('body')[0].appendChild(script);
    }(document, 'https://api.cartographer.drivecommerce.com/api/v3/runtime/client', function () {
    
        // Script has been loaded and Cartographer is now ready for use.
        var recommender = new Drive.GuidedRecommender({
            // etc.
        });
    
    }));
    
    

    Dynamic loading is a preferred method of integrating Cartographer, as it does not block page functionality while the script is loading and being initialized.

    Static Script Loading

    Add at the end of your body tag

    <script type="application/javascript" src="https://api.cartographer.drivecommerce.com/api/v3/runtime/client"></script>
    

    Page initialization code

    $(function () {
        // Cartographer is now ready for use.
        var recommender = new Drive.GuidedRecommender({
            // etc.
        });
    });
    

    The simplest method of integration comes at a cost of blocking page functionality while the script is loading, which may reduce overall page performance.

    Waiting for DOM Ready

    jQuery loaded in the head element

    <script>
        $(function () {
            // Load and initialize Cartographer script
        });
    </script>
    

    jQuery loaded at the bottom of the page

    <script>
        // Note: IE8 compatibility requires a more complex event handling.
        document.addEventListener('DOMContentLoaded', function (event) {
            // Load and initialize Cartographer script
        });
    </script>
    

    Most commonly, Cartographer recommenders are integrated into the site through available platform's CMS capabilities by placing required HMTL, CSS, and JavaScript snippets in some placeholder on the target page. This often results in Cartographer's integration code being rendered inline within the page HTML, with inline JavaScript being run immediately during page parsing, including code may use jQuery for its operations. This conflicts with the modern optimization recommendations to place all JavaScript near the end of the tag, including jQuery.

    In order to avoid running recommender code prematurely and thus failing, it is recommended to use one of the following techniques to defer script initialization.

    Reporting Conversions

    Cartographer does not force a specific way of adding products to the cart or completing checkout, leaving implementation details to the site integration layer. Thus, to provide accurate analytics and to be able to calculate runtime costs, Cartographer requires implementors to submit "add to cart" and "checkout complete" events.

    Add to Cart

    Submit Add to Cart event

    // Multiple products may be submitted at the same time.
    var submitData = [{ 
        productId: someProductId, 
        parentProductId: someParentId, 
        price: someProductPrice, 
        priceCurrency: somePriceCurrency, 
        quantity: 1 
    }];
    
    (function () {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://api.cartographer.drivecommerce.com/api/v3/runtime/addtocart?type=production&products=' + JSON.stringify(submitData) + '&time=' + (new Date().getTime());
        document.getElementsByTagName('body')[0].appendChild(script);
    })();
    

    Add to cart event shall be submitted whenever a customer selects a specific product and adds it to cart. Submitted data should be a semi-color separated list of four data elements:

    These four data elements should be repeated for all products that are being added to cart.

    Checkout

    Submit Checkout event

    // Multiple products may be submitted at the same time.
    var submitData = [{ 
        productId: someProductId, 
        parentProductId: someParentId, 
        price: someProductPrice, 
        priceCurrency: somePriceCurrency, 
        quantity: 1 
    }];
    
    (function () {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://api.cartographer.drivecommerce.com/api/v3/runtime/checkout?type=production&products=' + JSON.stringify(submitData) + '&time=' + (new Date().getTime());
        document.getElementsByTagName('body')[0].appendChild(script);
    })();
    

    Checkout events should be submitted after successfully completing the checkout. Please see Add to Cart section about required product data format.

    Custom Scripting and API Usage

    While out of the box Recommender experience aims to cover most common scenarios and user flows, it might be necessary at times to customize look and feel, or behavior of recommendations front-end. This section describes some ways that recommender could be tailors for customer specific needs.

    Initialization Options

        var recommender = new Drive.GuidedRecommender({
            project: 'project-draft-or-production-id',
    
            container: $('.placeholder'),
    
            recommendations: 5,
    
            languageCode: 'fr-CA',
    
            template: {
                templateName: 'override',
                ...
            },
    
            events: {
                eventName: function (data) {
                    // Handle event.
                    ... 
                },
                ...
            },
    
            translations: {
                'en': {
                    'add-to-cart': 'Add to Cart',
                    ...                
                },
                ...
            },
    
            helpers: {
                demoHelper: function (url) {
                    return url + '?demoHelperTest';
                },
                ...
            },
    
            ...
    
    Template Type Purpose
    project string Project's draft or production API key.
    savedSession string An ID of a saved session to be automatically replayed upon loading.
    container jQuery selector Targets page
    for placement of recommender front-end experience.
    recommendations number Number of recommended products to show.
    languageCode string, ISO language code such as 'en' Overrides default language detection logic and allows to force the specific language.
    templates hash Overrides standard templates, see Templates section.
    events hash Allows to handle recommender events and alter Cartographer behavior. See events section.
    translations hash Lightweight customization option for out-of-the-box templates. Instead of fully overriding the experience, it is possible to alter the copy of select elements, such as Add To Cart button caption. See Translations section for the list of available translation keys.
    helpers hash Enhance the functionality of Handlebars templates by providing JavaScript snippets for advanced data and text manipulation.

    Environment Configuration v3

    In some cases, it may be desirable to preset questions to already known value at the load time. This could be useful, for example, when some information is already known from the customer information. Alternatively, if a recommender is being reused on multiple pages of a site, and has a branching question that is dependent on the placement of the recommender, it might be desired to preselect a preferred path.

    environment initialization parameter facilitates this ability.

    Configuring Questions

        var recommender = new Drive.GuidedRecommender({
            ...
            environment: {
                questions: {
                    'question-slug-or-id': {
                        answers: [
                            'answer-slug-or-id',
                            'answer-slug-or-id',
                            ...
                        ]
                    }
                }
            }
        });
    
        // Start built-in flow.
        recommender.run();
    

    questions element of environment parameter allows preselecting question answers. When a question is prefilled, following things happen:

    See code example on the left for the sample usage. You can use either question and answer short codes (aka slugs) or their IDs in the configuration.

    Launching Recommendation Session

        var recommender = new Drive.GuidedRecommender({
            ...
        });
    
        // Start built-in flow.
        recommender.run();
    

    Recommender script instance is created in the paused state to allow advanced customization options. run method may be used to start customer session.

    Custom recommendations flow, and other deep customizations are outside of the scope of this document. Please contact Support for more details.

    API Concepts

    Summary v3

    The summary provides a quick overview of current user's answers and selections. The summary is updated whenever a question answer had changed, user backtracks through a questionnaire using the navigation or reset buttons, or state modifying API is invoked.

    The summary object is an array, with each entry representing a question answer.

    $(function () {
        // Cartographer is now ready for use.
        var recommender = new Drive.GuidedRecommender({
    
            // Listen to the update event and modify the UI accordingly.
            summaryUpdated: function (summary) {
                summary.forEach(function (entry) {
                    // Do something with the summary entry.
                    console.log(entry.questionDescription, ':', entry.answerDescription);
                });
            }
        });
    
        // Alternatively use the API method to retrieve summary on demand:
        var summary = recommender.summary();
    });
    
    Property Purpose
    questionId Related question ID.
    questionSlug Question's short code.
    questionDescription Localized question description text.
    answerType User's selection type. Can be one of 'text' or 'choice'.
    answerId Answer ID if answer type was 'choice'
    answerValue Answer value if answer type was 'text'
    answerSlug Answer short code if answer type was 'choice'
    answerSlug Answer short code if answer type was 'choice'
    answerDescription Localized answer description text if answer type was 'choice'

    Overriding Templates

    Override templates at initialization time

    $(function () {
        // Cartographer is now ready for use.
        var recommender = new Drive.GuidedRecommender({
            // Override templates
            templates: {
                // Render product name as H1 tag instead of H3 in the default implementation. Delegate link rendering to OOTB template.
                productname: '{{ref ""}}{{ref @root}} <h1><a href="{{> productlink this}}">{{product.name}}</a></h1>'
            }
        });
    });
    

    It is possible to customize recommender layout or look and feel, while retaining most of the built-in functionality, simply by overriding default templates. Cartographer uses Handlebars for client-size templates.

    Define new helpers at initialization time

    $(function () {
        // Cartographer is now ready for use.
        var recommender = new Drive.GuidedRecommender({
            // Override templates.
            templates: {
                // Show product name in lower case.
                productname: '{{lowerCase product.name}}'
            },
    
            // Provide helpers.
            helpers: {
                lowerCase: function (v) {
                    return (v || '').toLowerCase();
                }
            }
        });
    });
    

    In addition to overriding templates, it is possible to define new Handlebars helpers. See Optimizing Product Image Display section for a real life example.

    Available Templates

    Template Purpose
    main Main recommender shell
    header Custom content to be placed above other recommender content
    footer Custom footer content
    product Recommended product tile
    productaddtocart Product add to cart button
    productimage Product image container
    productimagemedia Product URL. See Optimizing Product Image Display section
    productlink Product detail page URL
    productmatch Indicator of recommendation fitness to user's answers to recommender questions
    productname Product name
    productprice Product pricing, including currency symbol
    question Question container
    questiongroup Question group (page) container
    questiongroupafter v2 Holds content to be inserted after other page content
    questiongroupbefore v2 Holds content to be inserted before any other page content
    questiongroupmiddle v2 Holds content to be inserted after main page content, but prior to navigation bar
    questionbreadcrumb v2 Renders single element of breadcrumbs bar
    questionbreadcrumbs v2 Renders breadcrumbs bar
    questiongroupnavigation Renders page navigation bar
    questiongroupnavigationafter v2 Holds content to be inserted after other page navigation content
    questiongroupnavigationbefore v2 Holds content to be inserted before any other page navigation content
    questiongrouptitle v2 Displays page title
    questionfreetext Free-text questions
    questionmultiplechoice General frame for multiple choice style questions
    questionmultiplechoicebuttons Renders multiple choice questions as buttons
    questionmultiplechoicemultiselect Renders multiple choice questions as a number of checkboxes
    questionmultiplechoicedropdown Renders multiple choice questions as a dropdown
    questionmultiplechoicedropdownplaceholder Placeholder text to be shown on dropdowns until user selects an option
    questionmultiplechoiceslider Renders multiple choice questions as value slider
    questionslider Renders slider type questions
    recommendations Product recommendations frame
    recommendationsheader Custom content to be placed above recommendations
    recommendationsfooter Custom content to be placed below recommendations
    recommendationsgroup v2 Displays recommendations page content
    recommendationsgroupfooter v2 Holds content to be inserted fatrother content on the results page
    recommendationsgroupheader v2 Holds content to be inserted before other content on the results page
    recommendationsgroupnavigation Renders results page navigation bar
    slidertick Value button on slider bar

    Examples

    Linking to Product Detail Pages (PDP)

    Generic product link template override example

        var recommender = new Drive.GuidedRecommender({
            // Override templates
            templates: {
                // Override product link template. product.externalId is available on the recommendation record and will contain master or child product ID.
                productlink: '/Product?pid={{product.externalId}}'        
            }
        });
    

    Use Demandware content functions to avoid hard-coding the URL and locale:

        var recommender = new Drive.GuidedRecommender({
            // Override templates
            templates: {
                // Override product link template. product.externalId is available on the recommendation record and will contain master or child product ID.
                productlink: "$url('Product-Show', 'pid', '')${{product.externalId}}"
            }
        });
    

    Use specific Magento URLs to avoid hard-coding the URL and locale:

        var recommender = new Drive.GuidedRecommender({
            // Override templates
            templates: {
                // Override product link template. product.externalId is available on the recommendation record and will contain master or child product ID.
                productlink: "/catalog/product/view/id/${{product.externalId}}"
            }
        });
    

    If recommendations are using basic product tile template that is included with Cartographer, one of the implementation steps is to enable correct PDP link generation. This is achieved by customizing productlink template as following (see example).

    Optimizing Product Image Display

    Saving Sessions v3

        var recommender = new Drive.GuidedRecommender({
            ...
        });
    
        // Save a session and receive session information back.
        recommender.saveSession(function (savedSessionKey, sessionDetails) {
            // Do something with saved sessions details and/or key.
            ...
        });
    
        // Retrieve previously saved session details.
        recommender.replaySession(savedSessionKey, function (sessionDetails) {
            // For example, replay the session and restore the quiz state.
            recommender.replay(sessionDetails.history);
        });
    

    It is possible to extract and save current quiz session details. This could be useful, for example, to implement a reminder or a quiz sharing email that a customer can sent to themselves. Saved sessions are identified by a randomly generated key that a host site can use to store and retrieve the session descriptor at the later time.

    Saved session details include information that enables a variety of uses: construct a link to view quiz results online, list product recommendations in an email, or provide a detailed description of customers answers and explanation of quiz results. Session details object will consist at least:

    Parameter Purpose
    history Array of history events. This can be used with replay method to restore the session state. The format is this data structure is internal to Cartographer and is not intended to be interpreted by the host site.
    summary A summary of customers answers.
    recommendations If a customer was provided with any recommendations, this will contain a list of recommended products and related product data.

    API Methods

    To support deeper customization, Cartographer provides a number of public API methods.

    currentProject v2

    Returns current project configuration.

    currentFactors v2

    Returns user input data vector, including both activated and non-activated answers.

    See afterUpdateFactor event for description of available factor data elements.

    currentActiveFactors v2

    Returns user input data vector, including only activated answers.

    isReplaying

    Returns whether Cartographer is currently in the replay state, such as when restoring recommendations state after returning to the recommender from visiting recommended product detail page.

    See History Replay section for the description of managing history state.

    replay

    Replays the provided history state array.

    Parameter Purpose
    events Array of history events

    saveSession v3

    Saves current session details.

    Parameter Purpose
    callback A callback to receive saved session key and session details.

    replaySession v3

    Retrieves previously saved session details. Use replay method to restore the previous quiz state.

    Parameter Purpose
    sessionKey Previously saved session key.
    callback A callback to receive saved session details.

    updateRecommendations

    Refreshes recommendations.

    deactivateQuestion

    Deactivates given question without removing user selections. This is useful when implementing custom page routing and it is necessary to preserve selected answers rather than clearing them when returning to earlier pages.

    Parameter Purpose
    $question DOM element containing the question

    undoQuestions

    Unlike deactivateQuestion method, removes user selections from given questions and updates history state.

    Parameter Purpose
    $questions jQuery list with DOM elements containing questions to remove selections from.

    Navigates to any page preceding the current page. Target page must have been passed through by the user on the way to the current page, meaning it is not possible to jump recommendation tree branches using this method. Automatically deactivates and removes user selection from pages.

    Only returning to the previously visited page is supported, and it is not possible to jump to not yet visited page.

    Parameter Purpose
    $page DOM element containing the target page

    restart v2

    Completely resets recommender state without reloading the page. As result of this method, all questions will be deactivated, user answers will be removed, and the first page will be displayed.

    summary v3

    Retrieves current summary description.

    Events

    Cartographer generates a number of events and notification throughout the lifecycle of recommender instances. These notifications include simple notifications that allow developers to enhance part of recommender experience or improve analytics trackers, and more complex events that enable deep functionality customization.

    afterInitialize

    Defer displaying of recommendations experience until it is fully loaded:

        var recommender = new Drive.GuidedRecommender({
            container: $('.placeholder'),
    
            events: {
                afterInitialize: function (recommender) {
                    $('.placeholder').fadeIn();
                }
            }
        });
    

    afterInitialize event is fired when using built-in lifecycle manager (see run method) after recommender has been fully loaded, rendered, and is ready to receive user input.

    afterUpdateFactor

    Reveal questions one-by-one instead of displaying all of them right away:

        var recommender = new Drive.GuidedRecommender({
            container: $('.placeholder'),  
    
            events: {
                afterInitialize: function () {
                    // Hide all questions except for the first one upon initialization.
                    $('.question').filter(':gt(0)').hide();
                },
                afterUpdateFactor: function (data) {
                    if (data.questionId) {
                        // Find changed question id.
                        var updatedQuestionIndex = $('.question[data-question-id="' + data.questionId + '"]').data('question-index');
                        // Activate next question.
                        var $nextQuestion = $('.question-' + (updatedQuestionIndex + 1));
                        if ($nextQuestion.length && !$nextQuestion.is('.visible')) {
                            $nextQuestion.slideDown();
                        }
                    }
                }
            }
        });
    

    afterUpdateFactor event is fired after recommendation input has changed for any reason, such as user answered a question, some value was selected programmatically, recommender state has been reset, etc.

    summaryChanged v3

    summaryChanged event is fired whenever there is a significant update to question answers.

    Event Parameter Purpose
    summary Summary object. summary method can also be used to retrieve the current summary.

    afterActivateQuestion

    afterActivateQuestion indicates that question has been activated, i.e. at least one (for multiple select question) answer has been selected

    Event Parameter Purpose
    options.question DOM element containing the question
    options.page DOM element containing the page
    options.pageIndex Page index
    options.pageLast Indicates whether this is a last page in the experience
    options.complete Indicates whether page is complete, e.g. all questions on the page have been answered

    afterDeactivateQuestion

    The counterpart to afterActivateQuestion, indicates that question has been deactivated and no longer has any answers selected.

    beforeRetrieveRecommendations

    Reveal questions one-by-one instead of displaying all of them right away:

        var recommender = new Drive.GuidedRecommender({
            container: $('.placeholder'),  
    
            events: {
                beforeRetrieveRecommendations: function (page) {
                    if (page.pageLast && page.complete) {
                        // Only retrieve recommendations on the last page, if was completed.
                        return false;
                    }
    
                    // Prevent Cartographer from loading recommendations.
                    return true;
                }
            }
        });
    

    beforeRetrieveRecommendations allows customizing whether to retrieve and display recommendations after question activation or deactivation.

    Event Parameter Purpose
    options.question DOM element containing the question
    options.page DOM element containing the page
    options.pageIndex Page index
    options.pageLast Indicates whether this is a last page in the experience
    options.complete Indicates whether page is complete, e.g. all questions on the page have been answered

    renderRecommendations

    renderRecommendations allows to override default processing of recommendations data and provide custom rendering instead of using built-in templates.

    afterRenderRecommendations

    When using out-of-stock product recommendation templates, afterRenderRecommendations notifications will be triggered after DOM has been updated with products content.

    afterImpression

    Triggered after a recommended product has been made visible to the site user, for example, if a product with shown above the fold or user has scrolled to reveal recommendations that are below the fold.

    Event Parameter Purpose
    productId Product ID
    parentProductId Parent product ID, if known

    historyChanged

    Notifies host page about user history changes. This can be used to improve overall site navigation experience, for example, to support Back browser button and enable returning to the recommendation list without having to start over.

    Event Parameter Purpose
    history Recommendation events history

    replayComplete

    Notifies host page when history replay has been completed, and all user selections have been applied.

    Event Parameter Purpose
    No parameters available

    addToCart

    Indicates that built-in template add-to-cart button has been triggered.

    Event Parameter Purpose
    productId Product ID to be added to cart, may be a variation ID
    parentProductId Parent product ID, if known
    name Product name
    price Product price as captured during the last product import
    priceCurrency Price currency

    Custom Page Routing

    Recommender experience may contain multiple "pages" (which are presented on the same site page) of questions. Unless Page Routing v2 is used, default Cartographer behaviour is to display them sequentially, while allowing site user to move to another page only after completing all questions on the page. While Cartographer page routing feature can allow to rather complex recommendation flows, this behavior can be customized using following events.

    enterPage

    Notifies host page after a user has entered a new page. Allows performing additional UX enhancements, such as page animations.

    Event Parameter Purpose
    options.page DOM element containing the page
    options.pageIndex Page index
    options.pageLast Indicates whether this is a last page in the experience
    options.complete Indicates whether page is complete, e.g. all questions on the page have been answered

    pageComplete

    pageComplete event notifies about the completion of all questions on the current page.

    Event Parameter Purpose
    options.currentPage Reference to DOM element containing completed page
    options.nextPage Next page as determined by routing events
    returns options.advance Set to true to automatically advance to the next page without having a user to click Next Page button

    routeAdvancePage

        var recommender = new Drive.GuidedRecommender({
            container: $('.placeholder'),  
    
            events: {
                routeAdvancePage: function (e) {
                    // Navigate from page one to page three.
                    if (e.currentPage.page.is('.slug-page-one')) {
                        e.nextPage = $('.recommender .slug-page-three');
                    } else {
                        // Cancel navigation and stay on the current page.
                        return true;
                    }
                }
            }
        });
    

    routeAdvancePage is called after site user has clicked on the Next button to advance to the next page, and is used to determine the next target page. The default behavior is to navigate to the next page in the list, but this may be overridden by providing an alternate page, or by canceling navigation altogether.

    routeReturnPage

    Similar to routeAdvancePage, this event can be used to determine target page to return to after the user has clicked on the Back button.

    beforeAdvancePage

    Triggered before playing an animation of advancing the page. This event may be used to provide additional page enhancement or interactivity, such as playing a video upon arriving to the specific page.

    beforeReturnPage

    Similar to beforeAdvancePage, this event will be triggered when returning to one of the previous pages.

    pageAnimation

    pageAnimation allows to customize page transition animations

    Event Parameter Purpose
    options.from Reference to DOM element containing current page
    options.top Reference to DOM element containing next page

    Third-Party Analytics Integration

    Cartographer includes a robust built-in analytics and tracks user sessions, product impressions, conversions, etc. However, Cartographer also provides an easy way of integrating third-party analytics packages to improve the capture and integrate recommendations into overall storefront metrics. This can be achieved by taking advantage of events model described above. Alternatively, developers may tap into the firehose metrics event notifications. Please consult Drive Commerce support for implementation.

    Listening For Firehose Metrics Events

    Listen to analytics events and write them to browser console

        $(document).on('drive::cartographer::metrics', function (e, events) {
            console.log('Cartographer Metrics:', JSON.stringify(events));
        });
    

    Attach event listener (via jQuery or another method) to listen to drive::metrics event.