首页 > 解决方案 > 使用来自 npm 的 Google Maps JavaScript API 绘制方向

问题描述

几年来的第一个 Javascript 代码,我尝试加载 Google Maps Javascript API npm包以尝试加载地图并在 2 个点(里尔和比亚里茨,经过巴黎和波尔多)之间绘制方向。我以来自 Google API 的错误结束,代码为 UNKNOWN_ERROR,消息为

由于服务器错误,无法处理路线请求。如果您再试一次,请求可能会成功。

不幸的是,我在过去的 48 小时内尝试了几次,但都没有成功。

配置.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();

但是,我遇到了这个奇怪的错误,我不知道如何解决它:/

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. 

标签: javascriptgoogle-mapsnpmgoogle-maps-api-3

解决方案


最终,问题出在打包机方面,即 Parcel。我已经构建了这个代码的 SvelteKit 版本,它就像一个魅力。由于 SwelteKit 使用 Rollup 作为捆绑器(和 Vite),我想这只是在撰写本文时要走的路。


推荐阅读