我正在使用react-google-maps开发一个小型React应用程序。 根据下面的链接,可以使用
useMapsLibrary
钩子加载特定的 Google API
https://visgl.github.io/react-google-maps/docs/api-reference/hooks/use-maps-library
我正在使用钩子加载
geocoding
API,但似乎 API 根本没有加载。
我查过:
控制台打印:
API Loaded: false
Maps.tsx:21 Status: NOT_LOADED
Maps.tsx:22 Geocoder Library: null
它根本不进入
handleGeocode
函数内部。怎么了?谢谢!
以下是React组件代码:
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
组件中未提供您的 APIKEY。
<APIProvider apiKey=<apiKey>>
<Map>
..
</Map>
</APIProvider>
而是在父组件中提供它,我认为它是地图
<APIProvider apiKey=<apiKey>>
<Maps>
..
</Maps>
</APIProvider>