Skip to content

Instantly share code, notes, and snippets.

@Devarshi87
Forked from chrisjlee/googlemaps.apxc
Created September 16, 2020 09:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Devarshi87/cc8f87d5a895ee733d8ff366f7b6de8d to your computer and use it in GitHub Desktop.
Save Devarshi87/cc8f87d5a895ee733d8ff366f7b6de8d to your computer and use it in GitHub Desktop.
Salesforce and Google Maps API to calculate distance borrowed from: http://bulkified.com/How+to+use+the+Google+Maps+API+in+Salesforce.com
public class googleMaps {
public String duration {get;set;}
public Integer travelTime {get;set;}
public Decimal distance {get;set;}
public googleMaps(
String address1,
String address2) {
String jsonResults = getJsonResults(address1, address2);
jsonResults = formatJsonResults(jsonResults);
updateJsonSections(jsonResults);
}
public String getJsonResults(
String address1,
String address2) {
HttpRequest req = new HttpRequest();
Http http = new Http();
req.setMethod('GET');
String url = 'https://maps.googleapis.com/maps/api/distancematrix/json'
+ '?origins=' + address1
+ '&destinations=' + address2
+ '&mode=driving'
+ '&sensor=false'
+ '&language=en'
+ '&units=imperial';
req.setEndPoint(url);
HTTPResponse resp = http.send(req);
String jsonResults = resp.getBody().replace('\n', '');
return jsonResults;
}
public String formatJsonResults(String value) {
value = value.replace('{', ', ');
value = value.replace('}', ', ');
value = value.replace('[', ', ');
value = value.replace(']', ', ');
value = value.replace('"', '');
return value;
}
public void updateJsonSections(
String jsonResults) {
List<String> jsonSections = jsonResults.split(', ');
for (Integer i = 0; i < jsonSections.size(); i++) {
jsonSections[i] = jsonSections[i].trim();
if (jsonSections[i].contains('duration:')) {
duration = parseDuration(jsonSections[i + 2]);
travelTime = parseTravelTime(duration);
}
if (jsonSections[i].contains('distance:')) {
distance = parseDistance(jsonSections[i + 2]);
}
}
}
public Decimal parseDistance(String value) {
value = value.replace('text: ', '');
value = value.replace(' mi', '');
value = value.replace(' ft', '');
value = value.replace(',', '');
value = value.trim();
return Decimal.valueOf(value);
}
public String parseDuration(String value) {
value = value.replace('text: ', '');
return value;
}
public Integer parseTravelTime(String value) {
Integer tmpMinutes = 0;
List<String> durationNodes = value.split(' ');
String prevDurationNode = '';
for (String durationNode : durationNodes) {
if (durationNode == 'day' || durationNode == 'days') {
tmpMinutes += Integer.valueOf(prevDurationNode) * 1440;
}
if (durationNode == 'hour' || durationNode == 'hours') {
tmpMinutes += Integer.valueOf(prevDurationNode) * 60;
}
if (durationNode == 'min' || durationNode == 'mins') {
tmpMinutes += Integer.valueOf(prevDurationNode);
}
prevDurationNode = durationNode;
}
return tmpMinutes;
}
}
public class test_ctrl_GoogleMaps_Accounts {
/* Constructor */
public test_ctrl_GoogleMaps_Accounts() {
updateAccounts();
}
/* Accounts */
public List<Account> accounts = new List<Account>();
public List<Account> getAccounts() {
return accounts;
}
public void updateAccounts() {
accounts =
[SELECT Id, Name, ShippingStreet, ShippingCity,
ShippingState, ShippingPostalCode, ShippingCountry
FROM Account
WHERE ShippingStreet <> ''
LIMIT 100];
}
/* Account Variables */
public String account1Id {get;set;}
public Account account1 {get;set;}
public String account1Address {get;set;}
public String account2Id {get;set;}
public Account account2 {get;set;}
public String account2Address {get;set;}
public void updateAccountVariables() {
for (Account a : accounts) {
if (a.Id == account1Id) {
account1 = a;
}
if (a.Id == account2Id) {
account2 = a;
}
}
}
public void updateAccountAddresses() {
account1Address = EncodingUtil.urlEncode(
+ account1.ShippingStreet + ' '
+ account1.ShippingCity + ', '
+ account1.ShippingState + ' '
+ account1.ShippingPostalCode + ' '
+ account1.ShippingCountry,
'UTF-8');
account2Address = EncodingUtil.urlEncode(
+ account2.ShippingStreet + ' '
+ account2.ShippingCity + ', '
+ account2.ShippingState + ' '
+ account2.ShippingPostalCode + ' '
+ account2.ShippingCountry,
'UTF-8');
}
/* Account Options */
public List<selectOption> getAccountOptions() {
List<selectOption> options = new List<selectOption>();
for (Account a : accounts) {
options.add(new selectOption(a.Id, a.Name));
}
return options;
}
/* Button Action */
public void btnCalculateDistance_Click() {
updateAccountVariables();
updateAccountAddresses();
googleMaps gm = new googleMaps(
account1Address,
account2Address);
distance = gm.distance;
duration = gm.duration;
travelTime = gm.travelTime;
}
/* Results */
public Decimal distance {get;set;}
public String duration {get;set;}
public Integer travelTime {get;set;}
}
<apex:page controller="test_ctrl_GoogleMaps_Accounts">
<apex:form >
<apex:pageBlock title="Google Maps">
<apex:pageBlockSection columns="1">
<apex:pageBlockSectionItem >
<apex:outputText value="Account #1" />
<apex:selectList value="{!account1Id}" size="1">
<apex:selectOptions value="{!accountOptions}" />
</apex:selectList>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputText value="Account #2" />
<apex:selectList value="{!account2Id}" size="1">
<apex:selectOptions value="{!accountOptions}" />
</apex:selectList>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom">
<apex:commandButton id="btnCalculateDistance"
value="Calculate Distance" action="{!btnCalculateDistance_Click}"
rerender="pbResults" />
</apex:pageBlockButtons>
</apex:pageBlock>
<apex:pageBlock id="pbResults" title="Results">
<apex:pageBlockSection columns="1">
<apex:pageBlockSectionItem >
<apex:outputText value="Distance (miles)" />
<apex:outputText value="{!distance}" />
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputText value="Duration" />
<apex:outputText value="{!duration}" />
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputText value="Travel Time (minutes)" />
<apex:outputText value="{!travelTime}" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment