Salesforce and Google’s Time Zone API Integration: Translating Coordinates into Time Zone Info

Salesforce and Google’s Time Zone API Integration: Translating Coordinates into Time Zone Info

Last Updated on July 14, 2023 by Rakesh Gupta

Big Idea or Enduring Question:

  • How can you leverage Google’s Time Zone API to automatically update a lead’s time zone information based on their geo-coordinates?

Objectives:

After reading this blog, you’ll be able to:

  • Create Named Credentials for outbound requests.
  • Set up Google Maps API Key to retrieve timezone information based on geo-coordinates using Google’s Time Zone API.
  • Initiate an outbound HTTP GET request utilizing Salesforce Flow without the need for code.
  • Manage the outbound request response and implement appropriate actions.
  • Validate the integration and ensure the data flow works correctly.
  • and much more

👉 Previously, I’ve penned several posts on the topic of interfacing Salesforce with a diverse range of systems. Why not check them out while you are at it?!

  1. Generate Barcode and QR Code in Salesforce
  2. Integrate Salesforce with OpenWeatherMap Using Salesforce Flow
  3. Verify and Standardize Salesforce Addresses with Google’s Address Validation API

Business Use case

Jestilla Zetkin is currently serving as a Salesforce Architect at Gurukul On Cloud (GoC).  The Sales Director has entrusted Jestilla with a unique challenge. The aim is to make certain that upon creation, Salesforce Leads (Created through Web-to-lead) are infused with exact time zone details, which are determined based on their respective geo-coordinates.

  1. The business use case requires us to use Google’s Time Zone API to update four specific fields on leads automatically:
    1. dstOffset (the offset for daylight-saving time in seconds)
    2. rawOffset (the offset from Coordinated Universal Time for the given location’s time zone)
    3. timeZoneId (a string that uniquely identifies the time zone)
    4. and timeZoneName (the long form name of the time zone)
  2. In the event of a failed response, institute a contingency action to create a task for the lead’s designated owner.

What is Google’s Time Zone API?

Chances are high that your customer base is spread across multiple time zones. This factor can greatly influence your interactions with them, especially when scheduling calls, meetings, or sending out automated messages. The Salesforce platform offers a highly adaptable environment to store and manage customer data, but by default, it doesn’t provide a way to automatically record the timezone of the lead based on their geographic coordinates.

Google’s Time Zone API is a service offered by Google as part of its Google Maps platform. The API provides time zone data for any location worldwide based on latitude and longitude coordinates. This service can be particularly useful for developers who need to adjust communication according to a lead’s or contact’s geographical location or for businesses operating across different time zones.

The Time Zone API provides the following information:

  • The time zone’s ID, as defined by the IANA Time Zone Database (for example, America/New_York).
  • The time zone’s name (for example, Eastern Daylight Time).
  • The time offset from Coordinated Universal Time (UTC) without considering Daylight Saving Time (rawOffset).
  • The time offset due to Daylight Saving Time (dstOffset).

Note that the Google Time Zone API is subject to charges, so it’s important to understand the cost implications before implementing it.

How Google’s Time Zone API Works?

Google’s Time Zone API works by taking latitude and longitude coordinates and returning time zone data in JSON format. Here is a basic example of how to use it.

The following HTTP GET request gets time zone information for a location at latitude 40.712776 and longitude -74.005974 (New York City), and assumes you are making the request at a certain timestamp (UNIX timestamp).

https://maps.googleapis.com/maps/api/timezone/json?location=40.712776,-74.005974&timestamp=1458000000&key=YOUR_API_KEY

In the request URL above, replace YOUR_API_KEY with your actual API key.

Here is a sample response in JSON format that the API might return:

{
   "dstOffset" : 3600,
   "rawOffset" : -18000,
   "status" : "OK",
   "timeZoneId" : "America/New_York",
   "timeZoneName" : "Eastern Daylight Time"
}

The response includes the following information:

  1. dstOffset: The offset for daylight-savings time in seconds. This will be zero if the time zone is not in daylight-savings time during the specified timestamp.
  2. rawOffset: The offset from UTC (not counting daylight savings time) in seconds.
  3. status: A string indicating the status of the request. “OK” means that the request was successful.
  4. timeZoneId: A string containing the “tz” ID of the time zone (e.g., “America/New_York”).
  5. timeZoneName: A string containing the long form name of the time zone (e.g., “Eastern Daylight Time”).

Remember, in the request URL, the timestamp parameter is required, and the location parameter expects latitude and longitude coordinates.

  1. Timestamp: The desired time as seconds since midnight, January 1, 1970 UTC. The Time Zone API uses the timestamp to determine whether or not Daylight Savings should be applied based on the location’s time zone.
  2. Location: A comma-separated latitude, longitude tuple, location=40.712776,-74.005974, representing the location to look up.

Also, don’t forget to include your API key.

Benefits of Using Google’s Time Zone API

Google’s Time Zone API offers a number of significant benefits, especially for developers and businesses that need to operate across different time zones. Here are some of the key benefits:

  1. Accuracy: Google’s Time Zone API provides accurate time zone data for any location worldwide. It takes into account both the ‘raw’ time zone and daylight savings time, ensuring you always have the correct local time.
  2. Ease of Use: The API is straightforward to use, requiring only latitude and longitude as inputs. It returns data in a structured JSON format, which is easy to parse and use in various applications.
  3. Global Coverage: The API provides time zone data for locations worldwide, making it useful for global businesses and applications with international user bases.
  4. Reliability: As a service provided by Google, it’s highly reliable, ensuring you have consistent access to time zone data when you need it.
  5. Integration: It can be integrated into a variety of applications and platforms, including mobile apps, web services, and CRM platforms like Salesforce. This allows for functionalities such as scheduling communications in different time zones, etc.
  6. Up-to-Date Information: Google continuously updates its databases, ensuring that the data returned by the Time Zone API, such as daylight savings changes, are always current.

By leveraging these benefits, businesses can enhance the customer experience, increase operational efficiency, and ensure accurate data logging, among other advantages.

Prerequisite

Before you start using the Time Zone API, you need a project with a billing account and the Time Zone API enabled. Here is a step-by-step guide to setting up your Google Cloud project and enabling the Time Zone API:

Step 1: Create or Select Your Project

  1. Navigate to the Google Cloud Console.
  2. If you have previously created a project, you can select it from the drop-down list at the top. If not, click on New Project at the top right.
  3. Give your project a name, and optionally, you can also edit the Project ID.
  4. Click Create to create the project.

Step 2: Set Up a Billing Account

You need to link a billing account to your project to use Google’s Time Zone API. Here’s how:

  1. In the Google Cloud Console, open the console left side menu and click Billing.
  2. If you have one or more billing accounts, choose an account and associate it with your project. If not, click on Create Account, fill out the form to create a new billing account, and then associate it with your project.

Step 3: Enable the Time Zone API

Once you have your project and billing account set up, you can enable the Time Zone API.

  1. In the Google Cloud Console, open the console left side menu and navigate to APIs & Services | Library.
  2. In the API Library, search for Time Zone API and select it.
  3. On the Time Zone API page, click Enable.

Step 4: Generate Your API Key

Finally, you need an API key to authenticate your requests to the Time Zone API.

  1. In the Google Cloud Console, open the console left side menu and navigate to APIs & Services | Credentials.
  2. Click on the + CREATE CREDENTIALS button at the top and select API Key.
  3. Your new API key will be created and displayed. Copy it and store it securely. You’ll need this key to make requests to the Time Zone API.

Now, your Google Cloud project is all set up, and you can start using the Google Time Zone API.

👉 While the Time Zone API supports OAuth 2.0 and Service Account for authentication, this guide focuses on the simpler API Key method for brevity. If you need a more secure or complex authentication method, please refer to Google’s official authentication documentation.

Automation Champion Approach (I-do):

While this can be solved using various automation tools like Apex Trigger and others, we will use Salesforce Flow and newly introduced HTTP Callout (GET) flow feature.

HTTP Callout pulls or sends data between the Salesforce database and an external system via Flow Builder without using code. You can set up direct integrations as needed without having to work with a developer or call a middleware tool, such as Mulesoft. After you configure the HTTP callout action in a flow, Flow Builder auto-generates an external service registration, an invocable action, and Apex Class that you can use to create an Apex-defined resource for flows. You can then use the data output of the API request as input within Flow Builder and across Salesforce.

You can use HTTP Callout to connect a flow to a variety of APIs.

  • Get address information using a map API
  • Get weather conditions with a weather service API
  • Generate the barcode with a barcode service API
  • Get payment authorization information with a payment processing API
  • and much more

Before discussing the solution, let me show you a diagram of the process at a high level. Please spend a few minutes going through the following Flow diagram to understand it.

Let’s begin building this automation process.

Guided Practice (We-do):

There are 3 steps to solve Jestilla’s business requirement using Record-Triggered After-Save Flow. We must:

  1. Create custom fields on the Lead to store the response
  2. Create a Named Credential
  3. Salesforce Flow
    1. Define flow properties for record-triggered flow
    2. Add a formula to calculate timestamp
    3. Configure an HTTP GET callout for Time Zone API
    4. Add a Decision element to check the response code
    5. Add an Update Records element to update the lead
    6. Add a Create Records element to create a Task for the Lead owner to handle error response

Step 1: Create Custom Fields on the Lead Object to Store the Response

In this step, we’ve established custom fields within the Lead Object. These will serve as repositories for the response data from the Google’s  Time Zone API.

Field Label Field API Name Data Type
dstOffset dstOffset__c Number (18,0)
rawOffset rawOffset__c Number (18,0)
Current Position Current_Position__c Geolocation
Time Zone Id Time_Zone_Id__c Text (255)
Time Zone Name
Time_Zone_Name__c Text (255)

Step 2: Create a Named Credential

  1. Click Setup.
  2. In the Quick Find box, enter Named Credentials, and then select Named Credentials.
  3. Click New Legacy.
  4. Fill out the page with the callout endpoint’s URL and authentication parameters.
  5. Click Save.

Step 3.1: Define Flow Properties

  1. Click Setup.
  2. In the Quick Find box, type Flows.
  3. Select Flows, then click on the New Flow.
  4. Select the Record-Triggered Flow option, click on Create
    1. Object: Lead
    2. Trigger the Flow When: A record is created
    3. Set Entry Conditions: All Conditions Are Met (AND)
    4. Row 1: 
      1. FieldCurrent_Position__Latitude__s
      2. Operator: Is Null
      3. Value: {!$GlobalConstant.False}
    5. Click + Add Condition
    6. Row 2: 
      1. FieldCurrent_Position__Longitude__s
      2. Operator: Is Null
      3. Value: {!$GlobalConstant.False}
    7. Optimize the Flow For: Action and Related Records
    8. Choose the Option to Include a Run Asynchronously path to access an external system after the original transaction for the triggering record is successfully committed.
  5. Click Done.

Step 3.2: Formula to Calculate Timestamp

  1. Under Toolbox, select Manager, then click New Resource to calculate the seconds since the Unix epoch (January 1, 1970, 00:00:00).
  2. Input the following information:
    1. Resource Type: Formula
    2. API Name: forN_Timestamp
    3. Data Type: Number
    4. Decimal Places: 0
    5. FormulaROUND((NOW() – DATETIMEVALUE(“1970-01-01 00:00:00”)) * 24 * 60 * 60, 0)
  3. Click Done.

Step 3.3: Configure an HTTP GET Callout Action

HTTP Callout guides you through entering the details about the HTTP web-based service or REST API endpoint that you’re connecting to. After you complete the configuration, you invoke the action in a flow.

  1. Under Run Asynchronously node, select Action.
  2. Click + Create HTTP Callout.
  3. Configure the external service that connects Salesforce to the HTTP-based API.
    1. Enter a Name for the external service.
    2. Select the named credential that you created in the step 2.
    3. Click Next.
  4. The next step is to configure the invocable action that you can use in Flow Builder or across Salesforce.
    1. For Label, enter the action that the callout performs.
    2. Method: GET
    3. Add the URL endpoint for the request.
      1. URL Path/maps/api/timezone/json
    4. Add query parameter keys if the API you’re calling has them. When you use this action in a flow, you input values for the defined keys.
      1. Click Add Key
        1. Key: location
        2. Data Type: String
        3. Required: True
      2. Click Add Key
        1. Key: timstamp
        2. Data Type: Integer
        3. Required: True
      3. Click Add Key
        1. Key: key
        2. Data Type: String
        3. Required: True
  5. Provide a sample API response body. Salesforce generates a data structure from the sample response.
    1. Navigate to Provide Sample Response section.
    2. Click New.
    3. Paste a sample JSON response.
      
      
      {
          "timeZoneName": "sample string",
          "rawOffset": 1,
          "timeZoneId": "sample string",
          "errorMessage": "sample string",
          "dstOffset": 1,
          "status": "sample string"
      }

    4. Click Review and confirm that the Apex data structure is correct.
    5. To make changes, edit the text in Sample JSON Response or select data types from the data structure.
    6. Click Review.
    7. Click Done.
  6. Click Save.
  7. Flow Builder creates the action and external service. The action is available in the Actions window in the flow.
  8. The next step is to add apex action generated by HTTP Callout setup in the previous steps. We will use the Action element.
    1. Label the new action OpenWeather Callout.
    2. Set Input Values

      1. key: YOUR_OpenWeather_API_KEY
      2. location: {!$Record.Current_Position__Latitude__s},{!$Record.Current_Position__Longitude__s}
      3. timestamp{!forN_Timestamp}
  9. Click Done.

Step 3.4: Using Decision Element to Check the Time Zone API Callout Response Code

Now we will use the Decision element to check the Time Zone API response code.

  1. On Flow Designer, click on the +icon and select the Decision element.
  2. Enter a name in the Label field; the API Name will auto-populate.
  3. Under Outcome Details, enter the Label the API Name will auto-populate.
  4. Condition Requirements to Execute OutcomeAll Conditions Are Met (AND)
    1. Row 1:
      1. Resource: {!Timezone_Callout.2XX.status}
      2. Operator: Equals
      3. Value: OK
    2. Add a new OUTCOME ORDER by clicking on the + icon to check Contact Provider response.
    3. Condition Requirements to Execute Outcome: Any Conditions Is Met (OR)
      1. Row 1:
        1. Resource: {!Timezone_Callout.2XX.status}
        2. Operator: Equals
        3. Value: INVALID_REQUEST
      2. Row 2:
        1. Resource: {!Timezone_Callout.2XX.status}
        2. Operator: Equals
        3. Value: OVER_DAILY_LIMIT
      3. Row 3:
        1. Resource: {!Timezone_Callout.2XX.status}
        2. Operator: Equals
        3. Value: OVER_QUERY_LIMIT
      4. Row 4:
        1. Resource: {!Timezone_Callout.2XX.status}
        2. Operator: Equals
        3. Value: REQUEST_DENIED
      5. Row 5:
        1. Resource: {!Timezone_Callout.2XX.status}
        2. Operator: Equals
        3. Value: UNKNOWN_ERROR
      6. Row 6:
        1. Resource: {!Timezone_Callout.2XX.status}
        2. Operator: Equals
        3. Value: ZERO_RESULTS
  5. Click Done.

Step 3.5: Adding an Update Records Element to Update the Lead

The next step is to update the lead’s fields to store the callout response. We will use the Update Records element. 

  1. On Flow Designer, below the Successful node, click on the +icon and select the Update Records element.
  2. Enter a name in the Label field; the API Name will auto-populate.
  3. For How to Find Records to Update and Set Their Values select Use the account record that triggered the flow
  4. Set Filter Conditions: None – Always Update Record
  5. Set Field Values for the Lead Records
    1. Row 1:
      1. Field: Time_Zone_Id__c
      2. Value: {!Timezone_Callout.2XX.timeZoneId}
    2. Click Add Field
    3. Row 2:
      1. Field: Time_Zone_Name__c
      2. Value: {!Timezone_Callout.2XX.timeZoneName}
    4. Click Add Field
    5. Row 3:
      1. Field: dstOffset__c
      2. Value: {!Timezone_Callout.2XX.dstOffset}
    6. Click Add Field
    7. Row 4:
      1. Field: rawOffset__c
      2. Value: {!Timezone_Callout.2XX.rawOffset}
  6. Click Done.

Step 3.6: Add Action – Create a Record to Handle Error Response

The next step is to create a task, for this, we will use the Create Records element.

  1. On Flow Designer, below the Failed node, click on the +icon and select the Create Records element.
  2. Enter a name in the Label field; the API Name will auto-populate.
  3. Input the following information:
    1. Enter Label the API Name will auto-populate.
    2. How Many Records to Create: One
    3. How to Set the Record Fields: Use separate resources, and literal values
    4. Object: Task
    5. Set Field Values for the Case
    6. Row 1:
      1. Field: Description
      2. Value: {!Timezone_Callout.2XX.status}
    7. Click Add Field
    8. Row 2:
      1. Field: OwnerId
      2. Value: {!$Record.OwnerId}
    9. Click Add Field
    10. Row 3:
      1. Field: Priority
      2. Value: High
    11. Click Add Field
    12. Row 4:
      1. Field: Status
      2. Value: Not Started
    13. Click Add Field
    14. Row 5:
      1. Field: Subject
      2. Value: {!Timezone_Callout.responseCode}
    15. Click Add Field
    16. Row 6:
      1. Field: WhatId
      2. Value: {!$Record.Id}
  4. Click Done.

In the end, Jestilla’s Flow will look like the following screenshot:

Once everything looks good, perform the steps below: 

  1. Click Save.
  2. Enter Flow Label the API Name will auto-populate.
  3. Click Show Advanced.
  4. API Version for Running the Flow: 58
  5. Interview Label: Get Timezone Info {!$Flow.CurrentDateTime}
  6. Click Save.

Almost there! Once everything looks good, click the Activate button.

👉 Check out the video for step-by-step instructions.

Proof of Concept

Going forward, whenever leads are generated through web-to-lead or any other method that includes the Current Position field (geo-coordinates), the record-triggered flow will be triggered to retrieve the timezone information using the Time Zone API.

Formative Assessment:

I want to hear from you!

What is one thing you learned from this post? How do you envision applying this new knowledge in the real world? Feel free to share in the comments below.

Have feedback, suggestions for posts, or need more information about Salesforce online training offered by me? Say hello, and leave a message!

 

6 thoughts on “Salesforce and Google’s Time Zone API Integration: Translating Coordinates into Time Zone Info

  1. I am getting a Syntax error for the formula:

    ROUND((NOW() – DATETIMEVALUE(“1970-01-01 00:00:00”)) * 24 * 60 * 60, 0)

    Also, what is this variable you used:

    varT_Key

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.