Mirror of https://github.com/roostorg/coop
github.com/roostorg/coop
1import { Loader } from '@googlemaps/js-api-loader';
2import { useEffect, useState } from 'react';
3
4// The key should be available at build time in VITE_GOOGLE_PLACES_API_KEY env.
5// It's not a secret key, though, so hardcoding it is fine.
6const placesApiKey = import.meta.env.VITE_GOOGLE_PLACES_API_KEY ?? '';
7
8// Use this variable to not load the Google APIs twice.
9let placesApiLoaded = false;
10
11export function useMapsApi() {
12 const [mapsApi, setMapsApi] = useState<
13 | {
14 type: 'LOADED';
15 autocompleteService: google.maps.places.AutocompleteService;
16 geocoderService: google.maps.Geocoder;
17 }
18 | { type: 'LOADING' }
19 | { type: 'ERROR'; error: Error }
20 >({ type: 'LOADING' });
21
22 useEffect(() => {
23 if (placesApiLoaded) {
24 setMapsApi({
25 type: 'LOADED',
26 autocompleteService: new google.maps.places.AutocompleteService(),
27 geocoderService: new google.maps.Geocoder(),
28 });
29 } else {
30 new Loader({ apiKey: placesApiKey, libraries: ['places'] }).load().then(
31 () => {
32 placesApiLoaded = true;
33 setMapsApi({
34 type: 'LOADED',
35 autocompleteService: new google.maps.places.AutocompleteService(),
36 geocoderService: new google.maps.Geocoder(),
37 });
38 },
39 (e: Error) => {
40 setMapsApi({ type: 'ERROR', error: e });
41 },
42 );
43 }
44 }, []);
45
46 return mapsApi;
47}