修复 "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

Fixing "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

我在 header 中包含了以下两个脚本,但出现错误 "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js key=************"></script>

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>

当我删除任一脚本时,我会收到其他 js 错误。如何在我的 rails 应用程序中正确重构这两个脚本?

在上面的示例中,您两次包含相同的脚本,但参数不同。您应该能够通过一次包含脚本以及所有必需的参数来解决您的问题:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&libraries=places&sensor=false"></script>    

如果您通过 ajax 调用调用 google 地图,则可以在退出调用地图的状态时使用 window.google = {}

我知道在我的情况下它不是 Rails 应用程序,但可能对其他人有帮助......我正在使用 React,当我在 [=20] 之间切换时遇到了同样的错误=].

就像 wLc 所说的那样,window.google = {} 非常有效,正在删除控制台中的错误,但 <script> 标记保留在 html 中,每次我添加时重新访问包含地图的页面。

componentWillUnmount 我添加了一些代码来删除标签。

const allScripts = document.getElementsByTagName( 'script' );
[].filter.call(
  allScripts, 
  ( scpt ) => scpt.src.indexOf( 'key=googleAPIKEY' ) >= 0
 )[ 0 ].remove();

 window.google = {};