Utilizing the Google Maps JavaScript API in npm to generate route directions

After not working with Javascript for a couple of years, I decided to try loading the Google Maps Javascript API npm package in order to display a map and draw directions between two points (Lille and Biarritz, passing through Paris and Bordeaux). Unfortunately, I encountered an error from the Google API with the code UNKNOWN_ERROR and the following message:

A directions request could not be processed due to a server error. The request may succeed if you try again.

Despite attempting multiple times in the past 48 hours, I have been unsuccessful.

config.js

export const API_KEY = 'XXXXXX___A_VALID_GOOGLE_API_KEY_HERE_XXXXXXX'
// the key has access to Directions API & Maps JavaScript API

index.js

import { API_KEY } from './config.js';
import { Loader } from '@googlemaps/js-api-loader';

//////////////////////
// Direction API Test
//////////////////////


const calculateAndDisplayRoute = async function (
  directionsService,
  directionsRenderer
) {
  try {
    const google = window.google; // Fix for ESLint Err google is not defined
    const res = await directionsService.route({
      origin: {
        query: 'Lille',
      },
      destination: {
        query: 'Biarritz',
      },
      waypoints: [
        { location: 'Paris, France' },
        { location: 'Bordeaux, France' },
      ],
      travelMode: google.maps.TravelMode.DRIVING,
      avoidTolls: true,
      avoidHighways: false,
      drivingOptions: {
        departureTime: new Date(Date.now()),
        trafficModel: 'pessimistic',
      },
    });
    console.log(res);
    directionsRenderer.setDirections(res);
  } catch (e) {
    console.log(`Directions request failed 
        Code: ${e.code} 
        Message: ${e.message} `);
  }
};

////////////
// API Load
////////////

const init = async function () {
  try {
    const loader = new Loader({
      apiKey: API_KEY,
      version: 'weekly',
    });

    const res = await loader.load();
    if (!res) return;

    const google = window.google; // Fix for ESLint Err google is not defined
    const directionsService = new google.maps.DirectionsService();
    const directionsRenderer = new google.maps.DirectionsRenderer();
    const map = new google.maps.Map(document.getElementById('map'), {
      zoom: 6,
      center: { lat: 47, lng: 2 },
    });

    directionsRenderer.setMap(map);
    document
      .getElementById('go')
      .addEventListener(
        'click',
        calculateAndDisplayRoute.bind(
          this,
          directionsService,
          directionsRenderer
        )
      );
  } catch (e) {
    console.error(e);
  }
};

init();

Unfortunately, I have been faced with this strange error and I'm unsure how to resolve it :/

Directions request failed 

Code: UNKNOWN_ERROR 
Message: DIRECTIONS_ROUTE: UNKNOWN_ERROR:
A directions request could not be processed due to a server error.
The request may succeed if you try again. 

Answer №1

After some investigation, it turned out that the issue stemmed from the bundler being used, specifically Parcel. I decided to transition to a SvelteKit setup for this project, and I must say, it's been smooth sailing ever since. With SvelteKit leveraging Rollup (along with Vite), it seems like the preferred option as of now.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 1.5's Ui-Router 1.0.0-beta.3 is missing a template configuration for 'resolve@root'

Struggling to make UI-Router's resolve method function properly, I'm encountering an error that I haven't been able to resolve. Error: No template configuration specified for 'resolve@root' Here is the definition of my stateProvid ...

Unable to transfer information from the Parent component to the Child component

Can you help me solve this strange issue? I am experiencing a problem where I am passing data from a parent component to a child component using a service method that returns data as Observable<DemoModel>. The issue is that when the child component ...

Could not locate module: The package path ./react is not exported from the package in E:NextAppportfolio_website-mainportfolio_website-main ode_modules ext-auth

I am encountering an issue while trying to import SessionProvider from Next-Auth. The error message that is being displayed is: "Module not found: Package path ./react is not exported from package E:\NextApp\portfolio_website-main\port ...

Different time parameter for setting a timeout in Javascript

I am struggling to create a slideshow with varying time intervals for each image. My knowledge of Javascript is limited, and I have been working on resolving this issue for quite some time. /* function ShowEffect(element){ new Effect.Appear(element, ...

Is there a way to verify the presence of data and halt code execution if it is not found?

In my data, there is a table containing a total of 5 links. The first 2 links can vary in availability as they are dynamic, while the last 3 links are static and are always displayed. The dynamic links' data is deeply nested within the state object, s ...

Is there a way to automatically change specific characters as a user types in an input field?

I'm facing an issue with replacing some characters dynamically. The goal is to ensure that user-input text is URL-friendly for constructing a URL: function slugify(string) { const a = "àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïí ...

The light/dark mode toggle is a one-time use feature

I've been experimenting with creating a button to toggle between light and dark modes on my website. Initially, it's set to light mode, but when I try switching to dark mode, it works fine. However, the issue arises when attempting to switch back ...

Unable to retrieve the following element in a JavaScript array

I am a beginner in JavaScript and I am attempting to access the next element of an array using an onclick function but so far I have not been successful. var i, len; function quiz() { var quiz_questions = [ "who is the founder of Fa ...

Include specific javascript files only for smartphones

Recently, I encountered an issue with a JavaScript code that swaps background images on scroll down. To address the problem with debounce, I ended up setting different debounce times for various browsers (I am aware this is not the ideal solution, but it&a ...

The occurrence of an unanticipated character '#' was found

I'm currently facing an issue while using webpack to load dependencies. Whenever I execute the npm run dev command, I encounter the following error: Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: ...

Can you explain the function of a digest attribute?

As a beginner in the world of NextJS, I am currently working on getting my first project ready for production. However, I encountered the following error: Application error: a client-side exception has occurred (see the browser console for more information ...

Tips for adding extra spacing between icon and text field using Vuetify

The code snippet below is used for the username section: <v-text-field prepend-icon="fas fa-user" height="60px" placeholder="Username" outlined ></v-text-field> Is there a way to add space between the user ...

What is the best way to retrieve information utilizing Http.get within my project?

I have a TypeScript file containing user data: File path: quickstart-muster/app/mock/user.mock.ts import {User} from "../user"; export const USERS:User[]=[ new User(....); ]; I have a service set up at: quickstart-muster/app/services/user.service.ts ...

Javascript Select Element with No Options

I'm currently working on a <select> element that is being populated from an array using the following code snippet: <select id="selector" name="selector"</select> <button type=button onclick=populateSelect(states)>Click me1!</ ...

Halting a function within a specific namespace

Is there a way to prevent certain characters from being entered during a keypress event for inputs when using a namespace in JavaScript? I noticed that even if the function returns false when the character is detected, the character still gets entered. How ...

Display an HTML tag with JavaScript

My code is in both HTML and TS files. The content stored in the Description variable looks like this: <div>aaaa</div><div>bbbb</div><div>cccc</div> Currently, the output displays as follows: aaaabbbbcccc I want to modi ...

"Exploring the magic of Vue.js and Three.js: A guide to seamlessly changing CSS style elements within an

I'm currently in the process of converting my Three.js project to Vue.js Within my Three.js scene, I have a 3D model with HTML points of interest attached to it. It is crucial that these points remain fixed to the model and consistently face the cam ...

Could the issue with the Testing Library render function not functioning be potentially linked to a dependency problem?

Currently working on developing a React app and incorporating testing with Jest and Testing Library. While the live server version of my app functions perfectly, I encounter an error when attempting to run test code. The 'render' function throws ...

Downloading multiple files on both iOS and Android devices

Is there a way to download assets (mp3/jpeg) in an Asynchronous manner? I have over 200 files in each case and the process is taking too long. Are there any techniques to speed up the download process on both iOS and Android? ...

jQuery carousel displaying a blank slide at the conclusion

I am experiencing an issue with my slideshow where it shows an empty slide after the last element. I suspect that there is something in my script causing this behavior, as it seems to be finding one extra child for the element and adding it as an empty spa ...