Loading...
Loading...

Google Maps React Hooks

Google Maps + React Hooks
Loading...
Loading...
2019-03-25
1 min read

From janosh.io

Google Maps + React Hooks

πŸ”— janosh.io Google Maps + React Hooks

♨️ Had to share this one since it is so nice and simple. If you are looking for a drop-in, zero-dependency Google Maps React component, look no further. Here it is:

src/components/map.js
jsx

To use it, simply grab a free Google Maps API key from πŸ”— Google cloud console (here is a guide for that) and either add it to your .env file or paste it in directly for GOOGLE_MAPS_API_KEY.

Then simply drop in the above Map component wherever you would like to display a Google map.

src/pages/page.js
js

To change the area shown by the map and its zoom level, pass it an options object containing the keys center and zoom.

src/hooks/addMarkers.jsx
jsx

If you would like to do something more fancy, for instance add some markers to the map, you can also pass in an onMount function:

src/hooks/addMarkers.js
jsx

link.coords should be an object of the same structure as center, i.e. with lat and lng keys for the latitude and longitude at which to display the marker.

Note that the onMount function must be curried since the Map component will itself provide the map object on which to apply the onMount to the inner function.

Optimization

By default, when using the Map component inside another functional component it will rerender whenever the parent component rerenders. Not only does this waste computational ressources since there’s no need to rerender the map if the changed props do not pertain to it, it also ruins the user experience since the map will jump back to its initial zoom level and center on every rerender. To prevent this, you can easily create a memoized map with the useCallback hook:

src/hooks/useCallback.js
jsx

In fact, you may want to make this part of the Map component by default, i.e.

diff
diff
Loading...
Loading...
Loading...
Loading...
Loading...