Using new google routes api - how can I render (show) route result to a map?

102 Views Asked by At

Using "old" google directions api we had directionsService for encapsulating rest query & directionsRenderer to show results to the map.

Directions API example for javascript:

    // 1. init route config
    let route = {
      origin: {
        ...
      },
      destination: {
        ...
      },
      ...
    }

    // 2. link map to renderer
    this.directionsRenderer.setMap(this.map);

    // 3. make request
    this.directionsService
    .route(direction)
    .then((response) => {
      // 4. render route on map
      this.directionsRenderer.setDirections(response);
    })

As for the new routes api: directionsService can be replaced by raw query code, but what about "directionsRenderer"? How can I apply response['routes'] to the map?

I can't see any examples in official docs, as well as no client library for JS.

1

There are 1 best solutions below

2
miguev On

The Google Maps JavaScript API does not currently provide a Routes API service or a renderer to display routes directly; there doesn't seem to be one yet, so you could file a feature request.

For now, you need to query the Routes API web service endpoints (REST or gRPC) either from JavaScript or through your own servers. A few examples were recently added to the Routes API documentation:

To facilitate querying the Routes API from your server applications, Routes API client libraries are available for Java, Go, Node.js, Python and .Net.

The recommended approach is to build your client-side applications so they call your own servers, let your servers query the Routes API, and secure your servers so that only your applications are allowed to query them (e.g. using Firebase App Check).

When querying the Routes API directly from JavaScript code, which is visible to users, API keys should be tightly restricted:

  • Restrict API keys to allow the necessary HTTP Referers.
  • Limit API requests per user to prevent unauthorized use and charges.
  • Keep JavaScript usage of Routes API in a separate project from server-side usage of Routes API, so that lower per-user limits can be applied on the project used (only) in JavaScript applications.
  • Make sure that all other API keys are restricted to specific APIs, so they may not be used on Routes API.