NAV

Introduction

Welcome to the Cartographer API!

Cartographer is a guided shopping tool that helps eCommerce customers purchase products that fit their specific needs, increasing conversion and reducing returns for retailers.

Functionality Overview

Question Types

Simple Choice

Map a single product attribute to a set of predefined answers. Questions can be rendered in the brower 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 product 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 allow to make Cartographer algorithm less retrictive, 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 a 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 to collect unstructured input from customers, such as names. Values entered in recommender sessions can be retrieved later using Cartographer reports. Free text questions have no effect on recommendations engine

Analytics Tracking.

Cartographer provides a number of 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:

Questionnaire Script Integration

Dynamic 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/v1/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/v1/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 is does not block page functionality while script is loading and being initialized.

Static Loading

Add at the end of your body tag

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

Page initialization code

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

Simplest method of integration, comes at a the cost of blocking page functionality while 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 capabilies by placing required HMTL, CSS, and JavaScript snippets in some placeholder on the target page. This results often 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 cart or completing checkout, leaving implementation details to the site integration layer. Thus, in order to provide an 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/v1/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/v1/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 a number of 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.
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 functionality of Handlebars templates by providing JavaScript snippets for advanced data and text manipulation.

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 in order 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.

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 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

Optimizing Product Image Display

API Methods

In order 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 description of managing history state.

replay

Replays given history state array.

Parameter Purpose
events Array of history events

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 preceeding 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 first page will be displayed.

Events

Cartographer generates a number of events and notification thoughout 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 recieve 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 changes for any reason, such as user answered a question, some value was selected programmatically, recommender state has been reset, etc.

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

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 to customize 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 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 user has entered new page. Allows to perform 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 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 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. Default behavior is to navigate to the next page in the list, but this may be overriden by providing an alternate page, or by cancelling navigation altogether.

routeReturnPage

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

beforeAdvancePage

Triggered before playing 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 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, convertions, etc. However, Cartographer also provides an easy way of integrating third-party analytics packages to improve capture and integrate recommendations into overall storefront metrics. This can be achieved by taking advantage of events model described above. Alternatively, developmers 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 brower 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.