Month: August 2018

  • Using Leaflet in a Power BI Custom Visual

    For some of the spatial visualisations I’ve been working with in Power BI, I’ve had to create Custom Visuals as the out-of-the-box and visuals in the AppSource don’t quite hit the mark. I’m quite fond of Leaflet for map rendering. Here’s how I got it working with a Power BI Custom Visual.

    Create a new Custom Visual via the Command Line:

    pbiviz new LeafletCustomVisual
    

    In the newly created directory, install Leaflet via npm:

    npm install --save leaflet
    

    You need the geojson as the typings for Leaflet (in the next step), depends on the package being available.

    Install typings for Leaflet:

    npm install --save-dev @types/leaflet
    

    As Power BI Custom Visuals don’t currently support modules, you will need to grab the Leaflet object from the window. Create an inject.js file with the contents:

    var L = window.L;
    

    Add the Leaflet package and inject.js file to pbiviz.json in the externalJS key:

    "externalJS": [
    "node_modules/leaflet/dist/leaflet.js",
    "inject.js",
    "node_modules/powerbi-visuals-utils-dataviewutils/lib/index.js"
    ],
    

    Import the Leaflet stylesheet to style/visual.less :

    @import (less) "node_modules/leaflet/dist/leaflet.css";
    

    In src/visual.ts, change the constructor to:

    private map: L.Map;
    
    constructor(options: VisualConstructorOptions) {
    console.log('Visual constructor', options);
    this.target = options.element;
    // Fill the target element with the Leaflet map
    this.target.style.width = "100%";
    this.target.style.height = "100%";
    
    if (typeof document !== "undefined") {
    this.map = L.map(this.target).setView([0, 0], 2);
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(this.map);
    }
    }
    

    You can find an example project on GitHub.