How to install google maps through npm?

对着背影说爱祢 提交于 2021-02-07 11:15:31

问题


Is there any package available on npm for google maps? Or am I really supposed to paste this

<script src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY">
</script>

to my index.html and download this js file on every refresh?

This is super annoying, because sometimes I get ReferenceError: google is not defined.


回答1:


Or am I really supposed to paste this to my index.html and download this js file on every refresh?

Yes. This is the only way to do so. There are some packages to dynamically do this for you, but the behavior is the same.

To reiterate, there is no official package for loading the Google Maps JavaScript for the web environment on NPM. The @google/maps referenced by others is for node only.

Update - 2020/01/17

I wrote @googlemaps/loader to help load the script dynamically and support promises.

google is not defined errors can be avoided by using the callback query parameter when loading the google maps script.




回答2:


The official google maps package (@google/maps) is for node only. In a browser environment, you need to use an unofficial package or include the official script on your site.

To the ReferenceError problem, make sure the script tag for google maps is above the script tag for your code so that it loads first. If it isn't, your script may run before the google global variable is created.

One unofficial package is google-maps, which can be used in a browser.




回答3:


The ReferenceError you're getting is likely because you're not calling the library the right way.

In Google's Documentation suggests that you should specify a callback (like initMap) which would be called when the API finishes loading. Anything you need to do with the Map should go within that function so that you ensure the API is loaded and google is already defined.

<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>



回答4:


Yes there are a few packages out there. You can try this one out.

npm - google maps




回答5:


I came across same problem when I was working with React + TypeScript. Firstly I installed Google Maps SDK with this line;

npm install @google/maps

But TypeScript compiler gave an error, also offered me this line to install;

npm install @types/google__maps

and then it worked.

import { createClient } from "@google/maps"

const googleMaps = createClient({
  key: "YOUR_API_KEY"
})


来源:https://stackoverflow.com/questions/46896362/how-to-install-google-maps-through-npm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!