We are pleased to announce two open source libraries that make it easier for you to use the Maps JavaScript API in modern web apps. Up until now, the Maps JavaScript API has required the use of a script tag inserted into the HTML document; however, this pattern requires careful selection of script tag attributes and a deep understanding of how the browser parses and executes JavaScript. To simplify things, we released the @googlemaps/js-api-loader and @googlemaps/react-wrapper modules on NPM.
The first library, @googlemaps/js-api-loader, dynamically loads the Maps JavaScript API and wraps the process in a Promise. This means you can now import the js-api-loader and load the Maps JS API via JavaScript rather than HTML. The loader also supports all of the options for loading the API, such as version, libraries, and apiKey, passed in as an options object. Other benefits include retries on network errors and a singleton pattern to avoid duplicate loads of the Maps JavaScript API. The following shows the usage of this library:
The second library, @googlemaps/react-wrapper, provides a React component you can use to wrap child components that require the MapsJavaScript API. The component will load the Maps JS API first to ensure the API is available, followed by your child components. This component accepts props matching the same options as @googlemaps/js-api-loader and it can safely be used many times in a web application. An example usage is below:
These libraries manage the insertion of the script tag into the HTML document and abstract away the asynchronous complexity into a Promise and React hook. The internal implementation matches the traditional pattern below:
For more information on script loading patterns, see the documentation in the Maps JavaScript API overview.
For more information on Google Maps Platform, visit our website.