Calculate distance between records (account city and contact city) in Salesforce.

Posted on October 10, 2021 Post Thumbnail

Yo Trailblazers,

In this blog post, I'm going to create a lightning component which calculate distance between Account City & Contact City with the help of Google Map Apis.

Check following image for demo.

DistanceCmp

What you'll Learn from Blog Post :)

1. Setup project on Google cloud platform.

2. Enable API which you want to use.

3. Setup credentials to access API.

4. How to make callout to rest api from Apex.

5. Parse returned response using Apex.

Walkthrough :)

1. First we need to setup project on Google Cloud Platform.

2. Enable Distance Matrix API.

3. Setup credentials to access API.

4. With the help of record id, query city.

5. At the end, We need to make callout and show response on record page.

Let's Start :)

Go to: https://console.cloud.google.com/

And create a project.

Project.

Go to your project > API & Services > + Enable API & Service

Api

Search for distance matrix api and enable it.

Enable

After enabling api > go to credentials and generate api key

setup

You may go for OAuth 2.0 but I'm going for API Key.

It requires billing account also, You may setup this, It's super easy.

After setting up everything we have API key for Authenticating our system with Google Apis.

Check following link for API Document:

https://developers.google.com/maps/documentation/javascript/distancematrix?hl=en_US

We'll get following response:

{  "originAddresses": [ "Greenwich, Greater London, UK", "13 Great Carleton Square, Edinburgh, City of Edinburgh EH16 4, UK" ],  "destinationAddresses": [ "Stockholm County, Sweden", "Dlouhá 609/2, 110 00 Praha-Staré Město, Česká republika" ],  "rows": [ {    "elements": [ {      "status": "OK",      "duration": {        "value": 70778,        "text": "19 hours 40 mins"      },      "distance": {        "value": 1887508,        "text": "1173 mi"      }    }, {      "status": "OK",      "duration": {        "value": 44476,        "text": "12 hours 21 mins"      },      "distance": {        "value": 1262780,        "text": "785 mi"      }    } ]  }, {    "elements": [ {      "status": "OK",      "duration": {        "value": 96000,        "text": "1 day 3 hours"      },      "distance": {        "value": 2566737,        "text": "1595 mi"      }    }, {      "status": "OK",      "duration": {        "value": 69698,        "text": "19 hours 22 mins"      },      "distance": {        "value": 1942009,        "text": "1207 mi"      }    } ]  } ]}

Now, Let's create aura component.

distanceCmp.cmp

<aura:component controller="DistanceHelper" implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
	 <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> 
    <aura:attribute name="distance" type="String"/>
    <aura:attribute name="timetotravel" type="String"/>
    <lightning:card iconName="standard:location" title="Distance / Time to Travel">
        
        <p class="slds-p-horizontal_small">
            <h1>Distance : {!v.distance} </h1> 
            <h1>Time to Travel : {!v.timetotravel} </h1>
        </p>
    </lightning:card>
</aura:component>

distanceCmpController.js

({
	doInit : function(component, event, helper) {
		var cId = component.get("v.recordId");
        //console.log(accId);
        var action = component.get("c.getDistance");
        action.setParams({
            "ConId":cId
        });
        action.setCallback(this, function(response) {
            //console.log(response.getReturnValue());
            var res = response.getReturnValue();
            component.set("v.distance",res[0]);
            component.set("v.timetotravel",res[1]);
        });
        $A.enqueueAction(action);
    }
})

Apex Class: DistanceHelper.Apxc

public class DistanceHelper {
    @AuraEnabled
    public static list<String> getDistance(String ConId) {
        
        list<String> resList = new list<String>();
        String endpoint = 'https://maps.googleapis.com/maps/api/distancematrix/json?';
        String apikey = 'AIzaSyADFxf2L7tKEtNRhVe9X1ZscvJRj372woY';
        contact c = [SELECT Id, account.billingcity, mailingcity FROM Contact Where Id =:ConId];
        String conCity = c.MailingCity;
        String accCity = c.Account.billingcity;
        system.debug(c);
        String mainUrl = endpoint +'origins='+ conCity +'&destinations='+ accCity +'&key='+ apikey;
        system.debug(mainUrl);    
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(mainUrl);
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        System.debug('response:--> ' + res.getBody());
        JSONParser parser =  JSON.createParser(res.getBody());
        while (parser.nextToken() != null) {
            if(parser.getText() == 'text') {
                System.debug('distance2'+ parser.getText());
                system.debug('Main temp_min-->' + parser.nextValue());
                resList.add(parser.getText());
                system.debug('Main temp_min--> ' + parser.nextValue());
            }
        }
        system.debug(resList);
        return resList;
    }
}

After creating all above files.

Add this component on contact record page.

This component only works on Contact Record Page.

thanks

If you have any question Ask Me

Thanks for Reading :)

Write a comment for suggestions and hit the heart icon.


651
0

Tags: #lightningComponent #salesforceIntegration #restApi

Comments

There are no comments yet.
Your message is required.

Get notified of new posts