Reading list Switch to dark mode

    Using Google API in Lightning Component

    Updated 19 December 2018

    This blog describes about,using google API in lightning component in salesforce. API key act as both a unique identifier and a secret token for authentication.

    Using Google API in Lightning Component

    As we all know that the use of Google API is restricted in Lightning component due to some security issue, although we can use it through iframe, and also do customizations in the map. You can refer to the code given below.

    Here is your Visualfoarce Page which you can include in lightning component later:

    <apex:page  applyHtmlTag="false" applyBodyTag="false" docType="html-5.0" showHeader="false" controller="GetRoute" standardStylesheets="false">
        
        <!-- 
        /**
         * Webkul Software.
         *
         * @category  Webkul
         * @author    Webkul
         * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
         * @license   https://store.webkul.com/license.html
         */
         -->
    
        <apex:includescript value="{!urlfor($Resource.JQuery)}"/>
        <html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" lang="en">
            <head>
                <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
                <meta charset="utf-8"/>
                <title>Directions service</title>
                <style>
                    html, body {
                        height: 100%;
                        margin: 0;
                        padding: 0;
                    }
                    #map {
                        height: 100%;
                    }       
                    #Mybutton{
                        display: none;
                    }
                </style>
            </head>
            <body>
                <apex:form >                
                    <apex:inputhidden id="start" value="{!startpoint}" />
                    <apex:inputhidden id="end" value="{!endpoint}"/> 
                    <button type="button" id="Mybutton">Mybutton</button>  
                </apex:form>
                <div id ="map"></div>
                <script>
                    function initMap() {
                        var directionsService = new google.maps.DirectionsService;
                        var directionsDisplay = new google.maps.DirectionsRenderer;
                        var map = new google.maps.Map(document.getElementById('map'), {
                            zoom: 7,
                            center: {lat: 41.85, lng: -87.65}
                        });
                        directionsDisplay.setMap(map);
                        var st;
                        var ed;
                        $( document ).on("click" ," #Mybutton ",function(){
                            st =$("[id$='start']").val();
                            ed =$("[id$='end']").val()
                            console.log($("[id$='start']").val());
                            calculateAndDisplayRoute(directionsService, directionsDisplay);
                        });
                        if($("[id$='start']").val()!=null && $("[id$='start']").val()!=st && $("[id$='end']").val()!=null && $("[id$='end']").val()!=ed){
                            $("#Mybutton").trigger("click");
                        }       
                    }
                    function calculateAndDisplayRoute(directionsService, directionsDisplay) {
                        directionsService.route({
                            origin: $("[id$='start']").val(),
                            destination: $("[id$='end']").val(),
                            travelMode: 'DRIVING'
                        }, function(response, status) {
                        if (status === 'OK') {
                            directionsDisplay.setDirections(response);
                        } else {
                            //window.alert('Directions request failed due to ' + status);
                        }
                    });
                    }
                </script>
                <script async="true" defer="true" src="https://maps.googleapis.com/maps/api/js?key=Your_Google_API_Key&callback=initMap">
                </script>
            </body>
        </html>
    </apex:page>
    
    The Controller 'GetRoute' used in the Visualforce Page:
    public with sharing class GetRoute {
    
        /**
         * Webkul Software.
         *
         * @category  Webkul
         * @author    Webkul
         * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
         * @license   https://store.webkul.com/license.html
         */
    
        public static string startpoint{get{
            startpoint = apexpages.currentpage().getparameters().get('startpoint');
            return startpoint;
        } set;}
        public static string endpoint{get{
            endpoint = apexpages.currentpage().getparameters().get('endpoint');
            return endpoint;
        } set;}
        
        public void nothing(){}   
    }

    Now we will switch to Lightning Component, here is the code:

    <aura:component >
    
        <!-- 
        /**
         * Webkul Software.
         *
         * @category  Webkul
         * @author    Webkul
         * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
         * @license   https://store.webkul.com/license.html
         */
         -->
    
        <ltng:require styles="{!$Resource.SLDS +
                 '/assets/styles/salesforce-lightning-design-system-ltng.css'}"/>
        <aura:handler name = "init" value="{!this}" action="{!c.doinit}"/>
        <aura:attribute name="startPoint" type="String"/>
        <aura:attribute name="endPoint" type="String"/>
        <aura:attribute name="frameSrc" type="String"/>    
        <div class="wk_static">
            <div class="site-masthead slds-page-header" role="banner">
                <div class=" slds-grid slds-wrap">
                    <div class="slds-col slds-has-flexi-truncate">
                      <div class="slds-media slds-no-space slds-grow">
                        <div class="slds-media__figure">
                        </div>
                        <div class="slds-media__body">
                          <h1 class="slds-page-header__title pageTitle slds-m-right--small slds-align-middle slds-truncate" title="this should match the Record Title">Using Google API in Lightning Component</h1>
                        </div>
                      </div>
                    </div>
                </div>
            </div>        
            <div class="slds-grid slds-grid--vertical-align-center slds-box slds-theme--shade">
                <div class="slds-size--1-of-2 slds-m-around--small">
                    <div class="slds-size--1-of-2 setmargin">
                        <div class="slds-form-element">       
                            <div class="slds-form-element__control">
                                <ui:inputselect aura:id="start" class="slds-select slds-m-bottom--small" labelclass="slds-form-element__label" value="{!v.startPoint}" label="Start" change="{!c.GetRoute}">
                                    <ui:inputSelectOption text="chicago, il" label="Chicago"/>
                                    <ui:inputSelectOption text="st louis, mo" label="St Louis"/>
                                    <ui:inputSelectOption text="joplin, mo" label="Joplin, MO"/>
                                    <ui:inputSelectOption text="oklahoma city, ok" label="Oklahoma City"/>
                                    <ui:inputSelectOption text="amarillo, tx" label="Amarillo"/>
                                    <ui:inputSelectOption text="gallup, nm" label="Gallup, NM"/>
                                    <ui:inputSelectOption text="flagstaff, az" label="Flagstaff, AZ"/>
                                    <ui:inputSelectOption text="winona, az" label="Winona"/>
                                    <ui:inputSelectOption text="kingman, az" label="Kingman"/>
                                    <ui:inputSelectOption text="barstow, ca" label="Barstow"/>
                                    <ui:inputSelectOption text="san bernardino, ca" label="San Bernardino"/>
                                    <ui:inputSelectOption text="los angeles, ca" label="Los Angeles"/>
                                </ui:inputselect>
                                <ui:inputselect aura:id="end" label="End" class="slds-select"  labelclass="slds-form-element__label" value="{!v.endPoint}" change="{!c.GetRoute}">
                                    <ui:inputSelectOption text="chicago, il" label="Chicago"/>
                                    <ui:inputSelectOption text="st louis, mo" label="St Louis"/>
                                    <ui:inputSelectOption text="joplin, mo" label="Joplin, MO"/>
                                    <ui:inputSelectOption text="oklahoma city, ok" label="Oklahoma City"/>
                                    <ui:inputSelectOption text="amarillo, tx" label="Amarillo"/>
                                    <ui:inputSelectOption text="gallup, nm" label="Gallup, NM"/>
                                    <ui:inputSelectOption text="flagstaff, az" label="Flagstaff, AZ"/>
                                    <ui:inputSelectOption text="winona, az" label="Winona"/>
                                    <ui:inputSelectOption text="kingman, az" label="Kingman"/>
                                    <ui:inputSelectOption text="barstow, ca" label="Barstow"/>
                                    <ui:inputSelectOption text="san bernardino, ca" label="San Bernardino"/>
                                    <ui:inputSelectOption text="los angeles, ca" label="Los Angeles"/>
                                </ui:inputselect>
                            </div>
                        </div>   
                    </div>
                    <div class="slds-size--4-of-8"></div>
                </div>
                <div class="slds-size--1-of-2 slds-m-around--small framediv">
                    <iframe id="myFrame" style="height: 100%;width: 100%" src="{!v.frameSrc}"/>
                </div>
            </div>
        </div>
    </aura:component>

    The Controller of lightning Component:

    Searching for an experienced
    Salesforce Company ?
    Find out More
    ({
        
        /**
         * Webkul Software.
         *
         * @category  Webkul
         * @author    Webkul
         * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
         * @license   https://store.webkul.com/license.html
         */
    
        doinit : function(component, event, helper) {       
            component.set("v.frameSrc",'https://wk-aakanksha-dev-ed--c.ap2.visual.force.com/apex/googleMap'); 
        },
        GetRoute: function(component, event, helper){
            var startpoint = component.find("start");
            var sp = startpoint.get("v.value");
            var endpoint = component.find("end");
            var ep = endpoint.get("v.value");
            
            var d = new Date();
            var n = d.getTime();
            component.set("v.frameSrc",'https://wk-aakanksha-dev-ed--c.ap2.visual.force.com/apex/googleMap?t='+n+'&startpoint='+sp+'&endpoint='+ep);
        }
    })

    Here is related CSS:

    /**
    * Webkul Software.
    *
    * @category  Webkul
    * @author    Webkul
    * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
    * @license   https://store.webkul.com/license.html
    */
    
    .THIS .framediv{
        height: 500px;
    }
    .THIS .site-masthead{
        background-color: #16325c!important;   
    }
    .THIS .pageTitle{
        color:#ffffff!important;
    }
    .THIS .setmargin{
        margin: 0 auto;
    }
    Note : If you want to know how to integrate google map with visualforce visit the following link How To Use Google Api Key In Visualforce

    Output

    using google API in lightning component

     

    Support

    That’s all for using google API in lightning component, still if you have any further query or seek assistance to make your salesforce classic apps compatible with lightning experience, feel free to add a ticket, we will be happy to help you. https://webkul.uvdesk.com/en/customer/create-ticket/

     

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    3 comments

  • David Roberts
    • Aakanksha Singh (Moderator)
      • David Roberts
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home

    Table of Content