Given two addresses on a Zoho Creator record — a pickup and a drop-off, a technician and a job site, a warehouse and a customer — the Google Distance Matrix API returns the driving distance between them. This function calls it from Deluge and writes the result back to the record in kilometres or miles, ready for mileage billing, route costing, or delivery-zone rules.
Rewritten from the 2016 original. The version in the original library used getUrl() and parsed the response by converting it to XML and running an XPath expression. getUrl() is legacy, and the XPath approach silently returns an empty string whenever Google reports ZERO_RESULTS or NOT_FOUND. The script below uses invokeurl, reads the JSON directly, and checks the per-element status before writing anything. It also drops the sensor=false parameter, which Google removed years ago.
Distance_Calc here) with address fields for both ends: Street/City/State/PostalCode and the matching Street1/City1/State1/PostalCode1.textDistance (single line) and Distance (decimal).void API.CalcDistance(int id)
{
d = Distance_Calc[ID == input.id];
// Build the origin and destination query strings
strAddress1 = "origins=" + d.Street + "," + d.City + "," + d.State + "," + d.PostalCode;
strAddress2 = "&destinations=" + d.Street1 + "," + d.City1 + "," + d.State1 + "," + d.PostalCode1;
apiKey = "YOUR_GOOGLE_MAPS_API_KEY";
strFullData = "https://maps.googleapis.com/maps/api/distancematrix/json?" + strAddress1 + strAddress2 + "&key=" + apiKey;
response = invokeurl
[
url : strFullData
type : GET
];
// Read the first element of the first row
rows = response.getJSON("rows");
if(rows != null && rows.size() > 0)
{
elements = rows.get(0).getJSON("elements");
if(elements != null && elements.size() > 0)
{
element = elements.get(0);
if(element.getJSON("status") == "OK")
{
distText = element.getJSON("distance").getJSON("text"); // e.g. "12.4 km"
distVal = element.getJSON("distance").getJSON("value"); // metres, integer
d.textDistance = distText;
d.Distance = distVal.toDecimal() / 1000; // km. Use / 1609.34 for miles.
}
else
{
info "Distance Matrix element status: " + element.getJSON("status");
}
}
}
else
{
info "Distance Matrix error: " + response.toString();
}
}
OK while an individual element is ZERO_RESULTS. Check the element status, as above, or you will store zeros for unroutable pairs.distance.value is always metres regardless of locale; distance.text is a formatted string that changes with the units parameter. Convert from the numeric value.origins=lat,lng and destinations=lat,lng if you already geocode.This script is part of the free Creator Scripts Deluge Library.
All 39 Deluge scripts, the full Zoho Creator course, and every downloadable asset are now free. Get free access →