Ruby-on-rails 修复“您在此页面上多次包含 Google Maps API。这可能会导致意外错误。”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29930274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:13:04  来源:igfitidea点击:

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

ruby-on-railsapimaps

提问by Hymanson Cunningham

I've included two below scripts in my header and I get the error "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

我在标题中包含了以下两个脚本,但出现错误“您在此页面上多次包含 Google Maps API。这可能会导致意外错误。”

<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>

When I remove either script, I get additional js errors. How can I properly refactor these two scripts in my rails app?

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

回答by QMFNP

In your example above, you're including the same script twice, but with different parameters. You should be able to solve your issue by including the script once, with all the required parameters like this:

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

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

回答by wLc

If you're calling google maps via an ajax call, you can use window.google = {}upon exiting the state in which the map was called.

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

回答by byverdu

I know that in my case it's not a Rails app but might help to someone else ... I'm working with React and I was getting the same error when I was switching between views/pages.

我知道就我而言,它不是 Rails 应用程序,但可能对其他人有帮助......我正在使用 React,当我在视图/页面之间切换时遇到了同样的错误。

And like wLc said window.google = {}worked like a charm and was deleting the error in the console but the <script>tag was remaining in the html and was added every time I was revisiting the page that has the map.

就像 wLc 所说的window.google = {}那样,它就像一个魅力,正在删除控制台中的错误,但该<script>标签仍保留在 html 中,并且每次我重新访问具有地图的页面时都会添加该标签。

On componentWillUnmountI've added some code to remove the tag.

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

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

 window.google = {};