ABSYZ ABSYZ

  • Home

    Home

  • About us

    Who We Are

  • Our Expertise

    What we Do

  • Our Approach

    How We Do It

  • Products

    What We Made

  • Industries

    Who We Do It For

  • Clients

    Whom We Did It For.

  • Article & Blogs

    What Experts Think

  • Careers

    Join The Team

  • Get In Touch

    Let’s Get Started

ABSYZ

Navigate to Google Map from Salesforce

Home / Article & Blogs / Google Maps / Navigate to Google Map from Salesforce
By Vikash Kumar inGoogle Maps, Salesforce

In
salesforce we have several requirement to navigate to Account location or Lead
location on google map. Mostly sales representative need to navigate to exact
account location. In most of the case we look to integrate google map with salesforce
which could be costly and will have some maintenance charge as we need to buy
google API subscription. Google map navigation can be done without integrating
salesforce with google but we have to know account geolocation  co-ordinate where we want to navigate.

 

To store the
Account geolocation co-ordinate, we need to create a custom field in account of
data type Geoloction. In this field we can store latitude and longitude of
account.

 

There is two
ways of populating this field

 

  1. By directly populating the value in account record.
  2. We can create a tab on account record page which set current location co-ordinate as geolocation.

Second option is only applicable if we are at account location.

 

 

 

Click on set Location to update the account record with current geolocation co-ordinate.

 

Above Location tab has visualforce page linked to Location Tab.

 

Find Visualforce page code below.

 

<apex:page standardController="Account" extensions="GetLocationInAccountController" >
    <!-- Begin Default Content REMOVE THIS -->
    <apex:form id="form">
        <h1>Welcome </h1> Your Location is<br/>
        
        Latitude is
        <div id="startLat">
        </div>
        Longitude is
        <div id="startLon">
        </div>
        <!--  <apex:commandbutton style="border-radius:20px;background: #7acdf2;" action="{!getpresentinfo}" value="Get Location"/>                         -->
        <!--   <apex:outputText value="The unformatted time right now is: {!dd}" /> -->
        <!-- <apex:commandbutton style="border-radius:20px;background: #7acdf2;"  onclick="ab(); return false;" value="checkin location"/> -->
        <apex:inputText id="Latitude" value="{!Lat}" Label="Latitude"/>
        <apex:inputText id="Longitude" value="{!Lon}" Label="Longitude"/>
        <apex:commandbutton action="{!location}" value="Set Location"/>     
    </apex:form>
    
    <script>
    window.onload = function ab() {
        var startPos;
        var geoSuccess = function(position) {
            startPos = position;
            document.getElementById('startLat').innerHTML = startPos.coords.latitude;
            document.getElementById('startLon').innerHTML = startPos.coords.longitude;
            document.getElementById('{!$Component.form.Latitude}').value=startPos.coords.latitude;
            document.getElementById('{!$Component.form.Longitude}').value=startPos.coords.longitude;
        };
        navigator.geolocation.getCurrentPosition(geoSuccess);
    };
    
    </script>
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script>     
        var geocoder = new google.maps.Geocoder();
    var latLng = new google.maps.LatLng(document.getElementById('{!$Component.form.Latitude}').value,
document.getElementById('{!$Component.form.Longitude}').value);
    
    if (geocoder) {
        geocoder.geocode({ 'latLng': latLng}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                console.log(results[0].formatted_address);
            }
            else {
                console.log("Geocoding failed: " + status);
            }
        });
    }    
    </script>
</apex:page>

Extension Code

 

public class GetLocationInAccountController
{
    private ApexPages.StandardController standardController;
    public Decimal Lat{get;set;}
    public Decimal Lon{get;set;}
    
    public GetLocationInAccountController(ApexPages.StandardController standardController)
    {
        this.standardController = standardController;
    }
    
    public PageReference  location(){
        ID recordid=standardController.getId();
        System.debug('ID--'+recordid);
        system.debug('Latitude---'+lat);
        System.debug('Longitude-----'+lon);
        list<Account> ss=new list<Account>();
        for(Account s:[select id,name,Geolocation__Latitude__s,Geolocation__Longitude__s from Account where id=:recordid]){
            s.Geolocation__Latitude__s=Lat;
            s.Geolocation__Longitude__s=lon;
            ss.add(s);
        }
        update ss;
        PageReference pageRef = new PageReference('/'+recordid);
        return pageRef.setRedirect(true);
        
    }
    
}

 

 

Once we have account record with geolocation we can create a lightning component which will have account name and buttons to navigate to google map from current location to account location and buttons to know the distance between current location to account location.

 

 

Click on Goto Map button to navigate to google map.

 

 

Code for the component is given below.

Component:

<aura:component controller="GoogleMapNavigationController" implements="force:appHostable, flexipage:availableForAllPageTypes, flexipage:availableForRecordHome, force:hasRecordId, forceCommunity:availableForAllPageTypes, force:lightningQuickAction" access="global" >
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="comLat" type="string"/>
    <aura:attribute name="comLong" type="string"/>
    <lightning:notificationsLibrary aura:id="notifLib"/>
    
    <!-- <aura:attribute name="RecId" type="String"/>-->
    
    
    
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    <aura:handler name="init" action="{!c.do}" value="{!this}"/>
    
    <!-- <lightning:button variant="brand" label="Refresh" title="Refresh" onclick="{! c.refresh }" />-->
    
    <div class="slds-grid slds-gutters slds-wrap">
        <div  class="slds-col slds-small-size--1-of-1  slds-medium-size--1-of-1 slds-large-size--1-of-1 slds-show_large">
            <lightning:card title=" Account Table" class="slds-card" aura:id ="changeTable">
                <lightning:datatable
                                     aura:id="tDataTable"
                                     columns="{! v.columns }"
                                     data="{! v.data }"
                                     keyField="Id"
                                     showRowNumberColumn="true"
                                     hideCheckboxColumn="true"
                                     onrowaction="{! c.handleRowAction }" />
            </lightning:card>
        </div>
    </div>
</aura:component>

JS Controller:

({
    doInit : function(component, event, helper) {        
        component.set('v.columns', [
            
            {label: 'Name', fieldName: 'Name', type: 'text'},
            
            
            {label:'Distance(KM)',type:'button',initialWidth: 135,typeAttributes:
             {label: 'Distance',name: 'Distance', title: 'Click to check distance'}
            },
            {label:'Redirect to Map',type:'button',initialWidth: 200,typeAttributes:
             
             {label: 'Goto Map',name: 'reDirect', title: 'Click to Visit'}
            },
            
            
        ]);
            navigator.geolocation.getCurrentPosition(function(position){
            component.set("v.comLat",position.coords.latitude);
            component.set("v.comLong",position.coords.longitude);
            console.log('l1--'+position.coords.latitude+'---l2---'+position.coords.longitude);
            
            });
            console.log('l1--'+component.get("v.comLat")+'---l2---'+component.get("v.comLong"));
            helper.fetchAccount(component, event, helper);
            
            },
            do: function (component, event, helper) {
            component.set("v.LoadSpinner",true);
            
            
            navigator.geolocation.watchPosition(function(position){
            component.set("v.comLat",position.coords.latitude);
            component.set("v.comLong",position.coords.longitude);
            var l1 = component.get("v.comLat"); 
            var l2 = component.get("v.comLong");
            
            console.log('l1--'+l1+'---l2---'+l2);
            component.set("v.LoadSpinner",false);
            
            });
            
            },
            handleRowAction: function (component, event, helper) {
            var action = event.getParam('action');
            var row = event.getParam('row');
            switch (action.name) {
            
            case 'Distance':
            helper.showDistance(component,row);
            break;
            case 'reDirect':
            helper.gotoMap(component,row);
            break;
            
            
            }
            }
            
            
            })

Helper

({
    fetchAccount : function(component, event, helper) {
        var action = component.get("c.fetchAccounts");
        action.setCallback(this,function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.data", response.getReturnValue());
                // component.set("v.LoadSpinner",false);
            }
        });
        $A.enqueueAction(action);
    },
    
    gotoMap : function(component,row){
        var l1 = component.get("v.comLat"); 
        var l2 = component.get("v.comLong");
        window.open("https://www.google.com/maps/dir/?api=1&origin="+l1+","+l2+"&destination="+row.Geolocation__Latitude__s+", "+row.Geolocation__Longitude__s+"&travelmode=driving");
    },
    showDistance: function(component,row){
        var l1 = component.get("v.comLat"); 
        var l2 = component.get("v.comLong");
        
        var radlat1 = Math.PI * l1/180;
        var radlat2 = Math.PI * row.Geolocation__Latitude__s/180;
        var theta = l2-row.Geolocation__Longitude__s;
        var radtheta = Math.PI * theta/180;
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        if (dist > 1) {
            dist = 1;
        }
        dist = Math.acos(dist);
        dist = dist * 180/Math.PI;
        dist = dist * 60 * 1.1515;
        dist = dist * 1.609344;
        console.log("Distance----="+dist);
        component.find('notifLib').showNotice({
            "variant": "success",
            "header": "Account Distance",
            "message": "Account is "+ dist + " KM away"
        })
        
        
        
    }
    
})

Apex Controller

public class GoogleMapNavigationController {
    
     @AuraEnabled
    public static List<Account> fetchAccounts(){
           return [SELECT
                Id, Name,Geolocation__Latitude__s,Geolocation__Longitude__s
                FROM Account];
        }
}

Replace geolocation custom field in Apex Controller with your custom field.

 

Google Map
108
Like this post
2 Posts
Vikash Kumar

Search Posts

Archives

Categories

Recent posts

BioAsia 2023 in Hyderabad: An Annual International Event

BioAsia 2023 in Hyderabad: An Annual International Event

The Role Of Marketing in Small & Medium Enterprises

The Role Of Marketing in Small & Medium Enterprises

Salesforce For Retail: How Salesforce CRM Can Help Retailers

Salesforce For Retail: How Salesforce CRM Can Help Retailers

What is ChatGPT & How Does It Work?

What is ChatGPT & How Does It Work?

What Is Graphic Design? (Executive Summary 2023)

What Is Graphic Design? (Executive Summary 2023)

  • Previous PostLWC with Aura Components,Calling controller from LWC,LDS in LWC
  • Next PostSalesforce CI/CD: Introduction to Gearset

Related Posts

Salesforce For Retail: How Salesforce CRM Can Help Retailers
Salesforce

Salesforce For Retail: How Salesforce CRM Can Help Retailers

Introduction To Copado Devops Tool
Salesforce

Introduction To Copado Devops Tool

What is Salesforce Code Builder?
Salesforce

What is Salesforce Code Builder?

Automation in Healthcare And Its Benefits
Health Cloud Salesforce

Automation in Healthcare And Its Benefits

Leave a Reply (Cancel reply)

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

*
*

ABSYZ Logo

INDIA | USA | UAE

  • About us
  • Article & Blogs
  • Careers
  • Get In Touch
  • Our Expertise
  • Our Approach
  • Products
  • Industries
  • Clients
  • White Papers

Copyright ©2022 Absyz Inc. All Rights Reserved.

youngsoft
Copy
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “ACCEPT ALL”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Privacy Policy
Cookie SettingsREJECT ALLACCEPT ALL
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.

CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.

Functional

Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.

Performance

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Analytics

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.

Advertisement

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.

Others

Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.

SAVE & ACCEPT