top of page

Calculate Driving Distance in Wix with Google Routes API

Writer: Faysal Jaali
Faysal Jaali
Jan 12, 2024
6 min read

Updated: Nov 2

For a new Wix distance-calculation feature, use Google’s Routes API rather than starting a new integration around the legacy Distance Matrix API. A route matrix returns travel distance and duration between origins and destinations.


Google marks Distance Matrix as a legacy product. Existing projects can remain supported, so first identify whether you are maintaining an existing integration or building a new one.


graphic green with text "Calculate distances using Wix Velo"

Define what “distance” means


Driving distance follows a road route. It is different from straight-line distance between coordinates. A delivery estimate, appointment travel charge and store locator can therefore require different calculations.


This example requests one driving route between two coordinate pairs. It does not geocode a typed address, include live traffic settings or calculate a delivery price.


Configure the project and secret


Enable Routes API in the appropriate Google Cloud project and configure billing, API-key restrictions and quotas for the application.


Store the key in Wix Secrets Manager as GOOGLE_ROUTES_API_KEY. Keep it on the backend. The Routes route-matrix guide documents the POST request, origins, destinations and response field mask.


Add a small backend method


Create backend/routes.web.js:


// backend/routes.web.js
import { webMethod, Permissions } from "@wix/web-methods";
import { secrets } from "@wix/secrets";
import { auth } from "@wix/essentials";
import { fetch } from "wix-fetch";

const readSecret = auth.elevate(secrets.getSecretValue);

function waypoint(latitude, longitude) {
  if (
    !Number.isFinite(latitude) || latitude < -90 || latitude > 90 ||
    !Number.isFinite(longitude) || longitude < -180 || longitude > 180
  ) throw new Error("Enter valid numeric coordinates.");
  return { waypoint: { location: { latLng: { latitude, longitude } } } };
}

export const calculateRoute = webMethod(
  Permissions.Admin,
  async (originLat, originLng, destinationLat, destinationLng) => {
    const body = {
      origins: [waypoint(originLat, originLng)],
      destinations: [waypoint(destinationLat, destinationLng)],
      travelMode: "DRIVE"
    };
    const { value } = await readSecret("GOOGLE_ROUTES_API_KEY");
    const response = await fetch(
      "https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-Goog-Api-Key": value,
          "X-Goog-FieldMask":
            "originIndex,destinationIndex,status,condition,distanceMeters,duration"
        },
        body: JSON.stringify(body)
      }
    );
    if (!response.ok) throw new Error("The route service request failed.");
    const rows = await response.json();
    const route = Array.isArray(rows) && rows.find(
      row => (row.originIndex ?? 0) === 0 && (row.destinationIndex ?? 0) === 0
    );
    if (
      !route || (route.status?.code ?? 0) !== 0 ||
      route.condition !== "ROUTE_EXISTS"
    ) throw new Error("No usable driving route was returned.");
    if (!Number.isFinite(route.distanceMeters)) {
      throw new Error("The route response has no distance.");
    }
    const seconds = Number(String(route.duration ?? "").replace(/s$/, ""));
    if (!/^\d+(\.\d+)?s$/.test(String(route.duration)) || !Number.isFinite(seconds)) {
      throw new Error("The route response has no usable duration.");
    }
    return { kilometers: route.distanceMeters / 1000, minutes: seconds / 60 };
  }
);

This example uses an administrator-only Wix web method for a controlled test. Import calculateRoute from backend/routes.web on an admin-only test page and pass four numeric coordinate values.


Read the response correctly


The request uses one origin and one destination. The result identifies the corresponding origin and destination indexes and verifies that a route exists before reading its distance and duration.


The returned kilometers and minutes are conversions for display. Do not label the duration as a traffic-aware arrival promise: the example does not request those settings.


A successful HTTP status is not enough on its own. A matrix response can contain a problem for a particular route, so the method checks the element’s status and condition.


example of UI for repeater displaying items and showing distance text
Original results-list illustration showing distances beside service options.

Add an address workflow only when needed


If visitors enter addresses, design a separate address-validation or place-selection step and use the relevant Google documentation. Do not silently treat an incomplete street name as a reliable delivery destination.


Show the interpreted origin and destination so the user can spot a mistake. Define what happens when the service cannot calculate a route.


example of UI for address input field when paris is selected
Original address-selection interface example for a distance-based service finder.

Before exposing a public calculator


Keep the admin test separate from a visitor-facing feature. A public calculator needs bounded requests, abuse protection and quotas. It should not allow unlimited origins and destinations or arbitrary expensive routing options.


If a calculated distance determines a price, keep the pricing rule on the backend and state whether the displayed amount is indicative or a confirmed quote. Keep a record of the business rule separately from the map provider’s response.


Test practical edge cases


Test valid coordinates, strings supplied instead of numbers, coordinates outside their valid ranges, an unavailable route, an API error and an unexpected response.


Local tests checked the request body, selected fields, response interpretation and validation using simulated responses. Real routes, account billing and the published Wix environment still need project-specific verification.


Set up a controlled coordinate test first


Create the backend/routes.web.js file shown above and store the API key under the exact secret name used by the code. Confirm that the Google Cloud project has the intended Routes API access, billing configuration and restrictions before making a real request.


In the administrator test, call calculateRoute with four numeric values: origin latitude, origin longitude, destination latitude and destination longitude. Keep that order visible in the test instructions. A latitude and longitude accidentally swapped can produce an invalid point or a location far from the intended place.


Begin with one known pair of public locations and one request. Inspect the returned kilometers and minutes before connecting the result to a larger interface. Do not infer a successful real route from a simulated response used in a local test.


Present the returned units clearly


The backend converts distanceMeters to kilometers and the duration string to minutes. The interface can round those values for readability, while retaining the unrounded values for any business rule that genuinely needs them. State the unit beside the number so a reader does not have to infer it.


For example, a hypothetical response of 12.345 kilometers and 18.5 minutes could be displayed as “12.3 km” and “about 19 minutes.” These are illustrative values, not a measured journey. The wording should remain an estimate and should not imply a guaranteed arrival time.


If distance affects a price, define whether the rule uses the rounded display value or the underlying result. A boundary such as a service radius needs a documented rule for exactly-on-the-boundary cases. Keep that decision on the backend rather than trusting an editable browser display.


Add address selection as a separate layer


The restored screenshots show an original service-finder interface with address selection and filters. Those controls illustrate a possible product design; they do not mean the single-route backend sample performs address search by itself.


If an address input is added, confirm which place the user selected and obtain the coordinate values through the supported address or place workflow. Show the interpreted destination before calculating a fee. An incomplete typed address should not silently become an assumed location.


Keep a useful fallback when a location cannot be resolved. Ask the user to select or correct the address rather than displaying a zero-distance result. Do not confuse an unavailable route with a destination located at the origin.


Extend the result into a locator carefully


A locator can combine one selected origin with a controlled list of business destinations. Keep destination coordinates with the records they identify, and map each returned result to the correct destination index. Do not assume every route is usable or that response order alone identifies the business record.


The route-matrix documentation describes the relationship between origins, destinations and route elements. Check current limits and account costs before expanding the number of pairs requested. A larger matrix creates more route elements than a single origin-destination request.


The original results-list image illustrates showing distance beside a service option. Include the service name and relevant availability information as well. The nearest road distance does not necessarily identify the best or available provider for a particular customer.


example of UI for address input field and filters
Original interface example combining address selection and filters. The backend sample in this guide calculates one route.

Distinguish an API error from an unusable route


The sample checks the overall HTTP response and the selected route element’s status and condition. A successful request can still contain an element that does not describe a usable route. Display an appropriate unavailable state and retain a safe diagnostic path for the administrator.


Try wrong input types, out-of-range coordinates, an unavailable route and a service error. Also check the interface’s loading and retry behavior. Disable uncontrolled repeated requests while one calculation is running, and avoid an automatic retry loop that can consume quota indefinitely.


Keep the published explanation aligned with the feature


Describe the travel mode and settings the integration actually requests. If it does not request traffic-aware settings, do not advertise live traffic estimates. If it calculates distance but not a final quote, label the result accordingly.


Review the feature after changing a Google Cloud project, API restriction or pricing rule. Keep the documented test pair and expected behavior with the integration record so the next editor can verify the complete path again.


Calculate matrix size before increasing the request


Origins

Destinations

Calculated route elements

1

1

1 × 1 = 1

1

10

1 × 10 = 10

5

10

5 × 10 = 50

10

20

10 × 20 = 200


Route elements are origin-destination pairs. These are calculated counts, not quoted current quotas or prices. Check the Google route-matrix documentation for the limits applying to the selected settings. A travel charge or service-radius rule belongs in a separately defined backend business rule.


Does the old API immediately stop working?


Legacy status does not mean every existing integration has stopped. Check the current policy and the configuration of the project being maintained.


Can I promise an exact arrival time?


A route duration is not a guarantee about traffic, appointments or operational delays. Match the wording to the data actually requested.


For custom mapping requirements, see our Wix map guide or contact CodeMasters.

bottom of page