How to install google maps through npm?
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>
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.
google is not defined errors can be avoided by using the callback query parameter when loading the google maps script.
Update - 2020/01/17
I wrote @googlemaps/js-api-loader to help load the script dynamically and support promises.
import { Loader } from '@googlemaps/js-api-loader';
const loader = new Loader({
apiKey: "",
version: "weekly",
libraries: []
});
loader
.load()
.then(() => {
new google.maps.Map(div, mapOptions);
})
.catch(e => {
// do something
});
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.