Calculate Distance Between Two Locations in ServiceNow (without an API call!)

I'm gonna keep this really quick --

If you need to calculate the distance between two Location records in the cmn_location table in ServiceNow, as long as both of those locations have latitude and longitude values, you can do so using the script below!

Usage examples at the bottom.

You can turn these functions into methods of a Script Include if you like; whatever boats your float, mate.

EDIT 3/26/25: Nevermind, I turned it into a Script Include for you. 😎

This is just for calculating raw distance; it's not for calculating actual driving distance or "drive time"/duration.

The main value for something like this is ruling things out. Like for example, if you're attempting to determine the optimal path between nodes A (starting point), B, and C, you could do GIS calls for all of that, but it would be expensive.
If, instead, you use the code below to do some pre-checks initially before sending the routing requests to the API, you can identify that location B is 2 miles from A, whereas C is 50 miles from A.
Therefore, you can assume that the routing will be A > B > C; with no expensive GIS API calls.

Adding more nodes further illustrates the point even further. You may be able to determine that A, B, C, and D are all within 5 miles of the starting point and each other, but location E is 10x that.
Therefore, you can optimize the location API queries and save yourself some spend. You thereby get a sort of factorial API cost savings.