cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
skizofre3e Member
Member

Use Google Map API in custom visual

hello,

I'm currently trying to display a google map on my custom visual that I'm developing.

In fact, I don't know how can I import the namespece, and the API.

Here is the code I'm trying to use :

 
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
      }
    </script>

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAyARcNvQVVfuYxt8JGT2ndho2_010AWkQ&callback=initMap"
    async defer></script>

  </div>
 
 
 

Thank you

1 ACCEPTED SOLUTION

Accepted Solutions
Moderator v-viig
Moderator

Re: Use Google Map API in custom visual

Hello @skizofre3e,

 

I suppose that you might use these code below and apply it to your case:

 

constructor(options: VisualConstructorOptions) {
    d3.select(options.element)
        .append('script')
        .attr({
            type: 'text/javascript',
            src: 'https://maps.googleapis.com/maps/api/js?key=AIzaSyAyARcNvQVVfuYxt8JGT2ndho2_010AWkQ',
            async: true
        })
        .on('load', () => {
            this.initMap();
        });

    this.element = options.element;
}

private initMap() {
    const google = window['google'] || window.window['google'];

    this.map = new google.maps.Map(this.element, {
        center: { lat: -34, lng: 150 },
        zoom: 8
    });
}
11 REPLIES 11
Community Support Team
Community Support Team

Re: Use Google Map API in custom visual

@skizofre3e, One way is to append the above html to options.element using JavaScript directly.
Community Support Team _ Sam Zha
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
skizofre3e Member
Member

Re: Use Google Map API in custom visual

@v-chuncz-msft I already tried that without any result .. Are you sure we can use APIs within custom visual ?

Community Support Team
Community Support Team

Re: Use Google Map API in custom visual

@skizofre3e,

 

Yes, I've tested it, though not very elegant.

Community Support Team _ Sam Zha
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
skizofre3e Member
Member

Re: Use Google Map API in custom visual

@v-chuncz-msft so what's wrong with my code ? if its working for you ? I cant get it xD

After several investigations I think the issue comes witht the wrraper "sanbox-host", since I need to put the div with a specific height.

Can you please Tell me how you did it ?

 

thank you very much for your help.

mhuancahuari Frequent Visitor
Frequent Visitor

Re: Use Google Map API in custom visual

Hola Skizofree,

No he usado google masp sobre powerBi, pero intentaste importar el typescript dentro del Proyecto CustomVisual que estas realizando?

 

Revisa esto aqui.

https://www.npmjs.com/package/@types/googlemaps

 

Luego mapea el TypeScript dentro de tu proyecto para que puedas utilizar esos tipos (verifica el archivo ".\typings\index.d.ts")

Segundamente deberás agregar la referencia al nuevo typescript instalado  algo como:
/// <reference path="globals/googlemaps/google.maps.d.ts" />

 

Luego en tu codigo visual.ts (nombre por defecto de tu archivo typescript)

ya puedes usar referencias a los objetos MVC de Google maps

como declarar  variables:

 

private myMap: google.maps.Map;

 

usar asignaciones de variables:

var marker = new google.maps.Marker({ position: myLatLng , map: myMap});

 

 

y no olvides insertar en tu código la instancia del script de google maps a la página como:

 

let script = document.createElement('script');
script.type = 'text/javascript';
script.src= "https://maps.googleapis.com/maps/api/js?libraries=visualization";
document.body.appendChild(script);

 

Si te fue bien, me comentas a marco.huancahuari@gmail.com

mhuancahuari Frequent Visitor
Frequent Visitor

Re: Use Google Map API in custom visual

llegaste a importar la libreria de TypeScript para Google Maps de NPM?

 

si no lo hiciste revisa este link

 

https://www.npmjs.com/package/@types/googlemaps

mhuancahuari Frequent Visitor
Frequent Visitor

Re: Use Google Map API in custom visual

Hola, llegaste a importar el typescript de google maps para npm?.

 

Si no lo hiciste revisa primero esto aqui: 

https://www.npmjs.com/package/@types/googlemaps

 

Luego debes de mapear el typescript dentro de tu definición de tipos en el archivo:

 

".\typings\index.d.ts"

 

Agrega la referencia alli, y luego podras usarlo en tu CustomVisual.

Community Support Team
Community Support Team

Re: Use Google Map API in custom visual

@skizofre3e,

 

See script below as an example.

        constructor(options: VisualConstructorOptions) {
			let mapDiv = document.createElement('div');
			mapDiv.id = 'map';
			mapDiv.style.height = "400px";
			options.element.appendChild(mapDiv);
			
			let js = document.createElement('script');
			js.innerHTML = "var map;"
							+ "function initMap() {"
							+ "map = new google.maps.Map(document.getElementById('map'), {"
							+ "center: {lat: -34.397, lng: 150.644},"
							+ "zoom: 8"
							+ "});"
							+ "}";
			options.element.appendChild(js);
			
			js = document.createElement('script');
			js.src='https://maps.googleapis.com/maps/api/js?key=AIzaSyAyARcNvQVVfuYxt8JGT2ndho2_010AWkQ&callback=initMap';
			options.element.appendChild(js);
Community Support Team _ Sam Zha
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
skizofre3e Member
Member

Re: Use Google Map API in custom visual

@v-chuncz-msft thank you very much; Its working now. I only have one more question. In your code you handled everything as innerHTML but can I embed this in my code for further processing for instance if I want to do calcustions, call classes and methods ... ? This is the code I was working on but not working :

 

module powerbi.extensibility.visual {


    /**
     * Function that converts queried data into a view model that will be used by the visual
     *
     * @function
     * @param {VisualUpdateOptions} options - Contains references to the size of the container
     *                                        and the dataView which contains all the data
     *                                        the visual had queried.
     * @param {IVisualHost} host            - Contains references to the host which contains services
     */

    export class BarChart implements IVisual {
        private div: d3.Selection<SVGElement>;
        private host: IVisualHost;
        private barChartContainer: d3.Selection<SVGElement>;
        private barContainer: d3.Selection<SVGElement>;
        private bars: d3.Selection<SVGElement>;
        private target: HTMLElement;
        private g: d3.Selection<SVGAElement>;
        private object:any;
        private css: d3.Selection<SVGAElement>;
        private script: d3.Selection<SVGAElement>;
        private map : google.maps.Map;



        static Config = {
            xScalePadding: 0.1,
        };

        /**
         * Creates instance of BarChart. This method is only called once.
         *
         * @constructor
         * @param {VisualConstructorOptions} options - Contains references to the element that will
         *                                             contain the visual and a reference to the host
         *                                             which contains services.
         */
        constructor(options: VisualConstructorOptions) {
            this.host = options.host;
            this.target = options.element;

         // this.target.innerHTML = "<script src=\"https://maps.googleapis.com/maps/api/js?key=AIzaSyAyARcNvQVVfuYxt8JGT2ndho2_010AWkQ&callback=initMap\",async defer></script>");

            let script = document.createElement('script');
            script.type = 'text/javascript';
            script.src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAyARcNvQVVfuYxt8JGT2ndho2_010AWkQ&callback=initMap";
            script.async = true;
            document.body.appendChild(script);


            this.div = d3.select(options.element)
            .append('div');

          

           
        }

        /**
         * Updates the state of the visual. Every sequential databinding and resize will call update.
         *
         * @function
         * @param {VisualUpdateOptions} options - Contains references to the size of the container
         *                                        and the dataView which contains all the data
         *                                        the visual had queried.
         */
        public update(options: VisualUpdateOptions) {
         //   let viewModel: BarChartViewModel = visualTransform(options, this.host);
            let width = options.viewport.width;
            let height = options.viewport.height;

            this.div.attr({id:"zakaria",width: width, height : height}); 
            
            function initMap(){
                this.map = new google.maps.Map(document.getElementById('zakaria'),{
                    center : {lat:-34,lng:150},
                    zoom : 8

                });

              
            }


        }

        /**
         * Destroy runs when the visual is removed. Any cleanup that the visual needs to
         * do should be done here.
         *
         * @function
         */
        public destroy(): void {
            //Perform any cleanup tasks here
        }
    }
}

whats wrong with it ? 

 

Thank you very much again (y)