I am using react-google-maps to develop a small React application.
As per the below link a particular Google API can be loaded using the useMapsLibrary
hook
https://visgl.github.io/react-google-maps/docs/api-reference/hooks/use-maps-library
I am using the hook to load the geocoding
API, but seems the API is not loading at all.
I have checked:
- The API key is correct.
- The API is enabled in the console.
- No restrictions on the API.
- It Doesn’t matter but the Map ID is also correct.
- The MarkerWithInfoWindow component is rendering fine with no issues.
Console prints:
API Loaded: false
Maps.tsx:21 Status: NOT_LOADED
Maps.tsx:22 Geocoder Library: null
It does not go inside the handleGeocode
function at all. What is wrong? Thanks!
Below is the React component code:
import {
APILoadingStatus,
APIProvider,
Map,
useApiIsLoaded,
useApiLoadingStatus,
useMapsLibrary
} from "@vis.gl/react-google-maps";
import MarkerWithInfoWindow from "./MarkerWithInfoWindow";
import {useEffect, useState} from "react";
const Maps = () => {
const geocoderLib = useMapsLibrary('geocoding');
const apiIsLoaded = useApiIsLoaded();
const status = useApiLoadingStatus();
const [markerPostion, setMarkerPosition] = useState({ lat: 53.54992, lng: 10.00678 });
useEffect(() => {
console.log("API Loaded:", apiIsLoaded);
console.log("Status:", status);
console.log("Geocoder Library:", geocoderLib);
const handleGeocode = () => {
console.log(`geocoderLib1`, status, apiIsLoaded, geocoderLib)
if (status !== APILoadingStatus.LOADED || !geocoderLib) return;
// const { country, city, address } = formData;
const fullAddress = `fullAddress`;
const geocoder = new geocoderLib.Geocoder();
void geocoder.geocode({ address: fullAddress }, (results, status) => {
if (status === 'OK') {
console.log(`Geocode successful: ${results}`);
// setMarkerPosition({ lat: location.lat(), lng: location.lng() });
setMarkerPosition({lat: 53.54992, lng: 10.00678})
// map.setCenter(location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
};
if (apiIsLoaded && status === APILoadingStatus.LOADED) {
handleGeocode();
}
}, [apiIsLoaded, status, geocoderLib])
return (
<APIProvider apiKey=<apiKey>>
<Map
style={{width: '50vw', height: '50vh'}}
defaultCenter={{lat: 53.54992, lng: 10.00678}}
zoom={5}
mapId=<mapId>
gestureHandling={'greedy'}
disableDefaultUI={true}
>
<MarkerWithInfoWindow position={markerPostion} />
</Map>
</APIProvider>
)
}
export default Maps