A lightweight React hook-based Flow-typed library for a simple Google Maps API usage.
As this article explains well, there is no official React library from Google for Google Maps, but there is a JS API Google Maps.
Adopting a library that allows using components like <Map />
and its children <Pinpoint />
<Circle />
etc... helps us by the point of view of code readability, but with some drawbacks:
So, the goal of this library is helping us to load the API via a hook and have the full control of Google Maps API, even when we use JSX components for an easier development.
This library does exactly that job: it loads google Maps API asynchronously, and it returns the google object. Period.
First, install the library:
npm install --save ya-google-maps-react
The library includes a helper Hook that returns the Google maps API.
The useGoogleApi
hook accepts:
key
: you must define it;libraries
: an array of libraries that you need to load. It defaults to places
.See src/index.dev.js for a full example:
import useGoogleAPI from './index';
// ...
const MyComponent = (): React.Node => {
const googleApi = useGoogleAPI('MY-API-KEY-HERE');
const mapRef = React.useRef(null);
// ...
React.useEffect(() => {
if (googleApi.google === undefined) return;
setMapInstance(
new googleApi.google.maps.Map(mapRef.current, {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
}),
);
}, [googleApi]);
// ...
if (googleApi.error)
return <div>An error occurred while loading the map.</div>;
}
If you have some issues, please make an issue on the issues tab and try to include an example.
git clone https://github.com/bertuz/ya-google-maps-react.git cd ya-google-maps-react npm install make watch
# NPM
$ npm i ya-google-maps-react --save
import useGoogleAPI from './index';
const MyComponent = (): React.Node => {
const googleApi = useGoogleAPI('MY-API-KEY-HERE');
const mapRef = React.useRef(null);
React.useEffect(() => {
if (googleApi === null) return;
new googleApi.maps.Map(mapRef.current, {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
}, [googleApi]);
}
Author: bertuz
Live Demo: View The Demo
Download Link: Download The Source Code
Official Website: https://github.com/bertuz/ya-google-maps-react
License: MIT