javascript - 使用来自 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.
解决方案
最终,问题出在打包机方面,即 Parcel。我已经构建了这个代码的 SvelteKit 版本,它就像一个魅力。由于 SwelteKit 使用 Rollup 作为捆绑器(和 Vite),我想这只是在撰写本文时要走的路。
推荐阅读
- python - Python:检查列表的最后一个值是否多次出现
- c++ - 在 UE4 中将原生 C++ 代码制作为蓝图
- angular - 如何将数据传递给通用角度组件(对话框)
- php - 如何通过路由传递数据并分配给laravel中的文本框?
- python - 如何读取匹配字符串并将结果拆分为多个文件
- r - 我无法在 shinyapps.io 上发布我的 Shiny 应用程序
- coldfusion - 从 ColdFusion 运行 ImageMagick 条件填充时出现问题
- python - 我的 GUI 在几个操作系统中的外观
- powershell - 带有消息命令行参数的强制标志
- c - C 中的素数:运行时错误