简体   繁体   English

在 React 应用程序的 Util 文件中初始化谷歌地图

[英]Initializing Google Maps in Util file in React app

I use Google Maps in my React app and handle all Maps API stuff in a util file.我在我的React应用程序中使用Google Maps ,并在一个util文件中处理所有Maps API内容。

In my index.html page, I link to Google Maps library -- see below:在我的index.html页面中,我链接到Google Maps地图库——见下文:

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

The problem I'm having is that in my util file, I'm getting "google is not defined" error -- see below.我遇到的问题是,在我的util文件中,出现“未定义谷歌”错误——见下文。 在此处输入图像描述

How do I handle this?我该如何处理? I'm linking to Google Maps library so I don't think I can import anything because it's not an npm package.我链接到Google Maps地图库,所以我认为我不能导入任何东西,因为它不是npm包。

Try adding window as a prefix:尝试添加窗口作为前缀:

const map = new window.google.maps.Map(document.createElement('div'));

If you including google maps with <script> you will get this warning in components too because Google Maps API is added to the global object (window).如果您使用<script>包含谷歌地图,您也会在组件中收到此警告,因为谷歌地图 API 已添加到全局对象(窗口)。 You can use window.google instead, or move to npm package created for Google Maps for example google-maps-react , @react-google-maps/api , react-google-maps .您可以改用window.google ,或移至为 Google 地图创建的 npm 包,例如google-maps-react@react-google-maps/apireact-google-maps

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM