Creación de mapas visuales personalizados con datos GeoJSON

Un usuario Pregunto ✅

gattoun1

Estoy en las primeras etapas de la creación de un mapa visual personalizado de Power BI. Por el momento, solo estoy tratando de mostrar un mapa de EE. UU. en blanco. Estoy usando datos de GeoJSON, que agregué a mi paquete de la siguiente manera:

  • Guardó el JSON en un archivo JavaScript y agregó var jsonData = {} alrededor.
  • Agregué este archivo JavaScript a una subcarpeta geojson en mi carpeta node_modules
  • Se agregó una referencia ExternalJS adicional a mi manifiesto: «node_modules/geojson/us-states.js»

Ahora estoy empezando a construir el visual de la siguiente manera:

module powerbi.extensibility.visual {
    "use strict";
    export class Visual implements IVisual {
        private host: IVisualHost;
        private svg: d3.Selection<SVGElement>;
        private div: d3.Selection<SVGElement>;
        private container: d3.Selection<SVGElement>;
        private json = JSON.parse((<any>window).jsonData);  

        constructor(options: VisualConstructorOptions) {

            this.svg = d3.select(options.element)
            .append('svg');
            this.container = this.svg.append("g")
                    .classed('container', true);
        }


        public update(options: VisualUpdateOptions) {
            let width: number = options.viewport.width; 
            let height: number = options.viewport.height;

            // D3 Projection
            var projection = d3.geo.albersUsa()
                   .translate([width/2, height/2])    // translate to center of screen
                   .scale(1000);          // scale things down so see entire US

// Define path generator
            var path = d3.geo.path()               // path generator that will convert GeoJSON to SVG paths
                .projection(projection);  // tell path generator to use albersUsa projection

//Create SVG element and append map to the SVG
            this.svg.attr({                width: width,                height: height
            });

            this.svg.selectAll("path")
                .data(this.json.features)
                .enter()
                .append("path")
                .attr("d", path)
                .style("stroke", "#fff")
                .style("stroke-width", "1")
        }
    }
}

El visual está en blanco. No hay errores en la consola. Esperaba depurar usando esto: https://microsoft.github.io/PowerBI-visuals/docs/how-to-guide/how-to-debug/ , pero el código proporcionado allí produjo numerosos errores y creo que ha quedado obsoleto según un comentario en esa página.

¡Gracias!

v-viig

Sugerimos usar «Pausa en la excepción Caugh» para comprender qué problema produce el código:

Cromo

  • Abrir herramientas de desarrollador (F12)
  • Ve a la Sources pestaña
  • Haga clic en el break on exceptions icono (señal de alto con un símbolo de pausa)
  • Compruebe el Pause On Caught Exceptions caja

imagen.png

Ignat Vilesov,

Ingeniero de software

Imágenes personalizadas de Microsoft Power BI

pbicvsupport@microsoft.com

gattoun1

En respuesta a v-viig

/*
 *  Power BI Visual CLI
 *
 *  Copyright (c) Microsoft Corporation
 *  All rights reserved.
 *  MIT License
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the ""Software""), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */


 
module powerbi.extensibility.visual {
    "use strict";
    export function logExceptions(): MethodDecorator {
        return function (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>)
            : TypedPropertyDescriptor<any> {

            return {
                value: function () {
                    try {
                        return descriptor.value.apply(this, arguments);
                    } catch (e) {
                        console.error(e);
                        throw e;
                    }
                }
            }
        }
    }


    export class Visual implements IVisual {
        private host: IVisualHost;
        private svg: d3.Selection<SVGElement>;
        private div: d3.Selection<SVGElement>;
        private container: d3.Selection<SVGElement>;
        private json = JSON.parse((<any>window).jsonData);  

       
        constructor(options: VisualConstructorOptions) {

            this.svg = d3.select(options.element)
            .append('svg');
            this.container = this.svg.append("g")
                    .classed('container', true);
        }
        
        @logExceptions()
        public update(options: VisualUpdateOptions) {
            let width: number = options.viewport.width; 
            let height: number = options.viewport.height;
            console.log('Json:', this.json);
            debugger;

            // D3 Projection
            var projection = d3.geo.albersUsa()
				   .translate([width/2, height/2])    // translate to center of screen
				   .scale(1000);          // scale things down so see entire US
        
// Define path generator
            var path = d3.geo.path()               // path generator that will convert GeoJSON to SVG paths
		  	    .projection(projection);  // tell path generator to use albersUsa projection

//Create SVG element and append map to the SVG
            this.svg.attr({
                width: width,
                height: height
            });
        
            this.container.selectAll("path")
                .data(this.json.features)
                .enter()
                .append("path")
                .attr("d", path)
                .style("stroke", "#fff")
                .style("stroke-width", "1")
        }
    }   
}

Agregué algunas funciones de depuración arriba. Si configuro las herramientas de desarrollo para que se detengan en cada excepción, se detiene cientos de veces antes de que se cargue la página. Si no hago una pausa en cada excepción, lo único que aparece en la consola es esto:

Uncaught TypeError: Cannot read property 'dataview' of undefined
    at <anonymous>:67:73
    at <anonymous>:94:15
    at <anonymous>:95:11
    at <anonymous>:96:7
    at Window.<anonymous> (<anonymous>:97:3)
    at <anonymous>:217:20
    at Object.i [as injectJsCode] (VM3514 visualhostcore.min.js:2)
    at r (VM3515 visualsandbox.min.js:1)
    at i.loadWithoutResourcePackage (VM3515 visualsandbox.min.js:1)
    at i.executeMessage (VM3515 visualsandbox.min.js:1)

v-viig

En respuesta a gattoun1

¿Puedes compartir el código fuente completo?

Ignat Vilesov,

Ingeniero de software

Imágenes personalizadas de Microsoft Power BI

pbicvsupport@microsoft.com

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *