Get the Distance Matrix
The GetDistanceMatrix() Apex method takes a set of locations and returns the estimated travel distance in meters and the time in seconds between the locations.
With two locations A and B, you can use this method to return matrices of travel distance and times between A–B and B–A. The diagonal elements of the matrices A–A and B–B are zero because the travel distance and the time from one spot to the same spot is zero.
The values for A–B and B–A can differ because the returning path isn’t always the same. The travel times are calculated for eight predefined time windows based on historical traffic data. Each time window has its own travel time matrix.
Where,
mapsis the namespace that’s available after you install Salesforce Maps.APIis the class that contains the global methods exposed to developers.GetDistanceMatrix()is the method.
Include as many as 20 locations. To catch exceptions, put a try-catch block around your code.
This code finds the estimated travel distance in meters and time between two grocery stores.
If you invoke methods within a flow, process builder, or trigger, avoid uncommitted work errors when you perform one of the following.
- Call the methods through a future method
- Call the methods as queueable
Uncommitted work errors can also arise if calling out to Salesforce Maps methods more than one time in a single transaction and the Salesforce Maps token hasn’t refreshed in the last 24 hours. If these errors occur, separate each callout into individual transactions.
Different processes refresh the token, such as plotting a route or schedule. The refresh process is almost immediate after each qualifying action occurs.
Although the return value is an Apex Map<String, Object> object, this JSON response illustrates the essential data that you receive in the resulting map.