Google 地图距离 API 在反应中未定义

Google Maps Distance API is undefined in react

我正在尝试使用 Google 地图距离矩阵服务 (https://developers.google.com/maps/documentation/javascript/distancematrix)。

我把这行放在我的public/index.html中:<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY"></script>

在 React 的 js 文件中,我可以打印 window.google 并查看全局变量。我还可以看到它有一个函数 window.google.maps.DistanceMatrixService() 来创建服务。但是,当我使用 var service = window.google.maps.DistanceMatrixService() 创建该服务时,serviceundefined。知道为什么吗?

正如 Jaromanda X 指出的那样,我错过了 new 关键字。

全行现在是:var service = new window.google.map.DistanceMatrixService().