简体   繁体   中英

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.

In my index.html page, I link to Google Maps library -- see below:

<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. 在此处输入图像描述

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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