我已经在 React JS 中编写了这段代码,以使用“react-google-maps/api”来计算两点之间的路线。现在我的谷歌地图不断重新渲染,直到出现“DIRECTIONS_ROUTE:OVER_QUERY_LIMIT”错误。我不知道是什么问题。帮助将不胜感激,因为我是 react 和 google-API 的初学者,而且我还没有在 react 中找到很多 google API 的指南。
这是我的代码:
import React from "react";
import {
GoogleMap,
useLoadScript,
DirectionsService,
DirectionsRenderer,
} from "@react-google-maps/api";
const libraries = ["places", "directions"];
const mapContainerStyle = {
width: "100%",
height: "50vh",
};
const center = {
lat: 31.582045,
lng: 74.329376,
};
const options = {};
const MainMaps = () => {
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: "********",
libraries,
});
const [origin2, setOrigin2] = React.useState("lahore");
const [destination2, setDestination2] = React.useState("gujranwala");
const [response, setResponse] = React.useState(null);
const directionsCallback = (response) => {
console.log(response);
if (response !== null) {
if (response.status === "OK") {
setResponse(response);
} else {
console.log("response: ", response);
}
}
};
const mapRef = React.useRef();
const onMapLoad = React.useCallback((map) => {
mapRef.current = map;
}, []);
if (loadError) return "Error loading maps";
if (!isLoaded) return "loading maps";
const DirectionsServiceOption = {
destination: destination2,
origin: origin2,
travelMode: "DRIVING",
};
return (
<div>
<GoogleMap
mapContainerStyle={mapContainerStyle}
zoom={8}
center={center}
onLoad={onMapLoad}
>
{response !== null && (
<DirectionsRenderer
options={{
directions: response,
}}
/>
)}
<DirectionsService
options={DirectionsServiceOption}
callback={directionsCallback}
/>
</GoogleMap>
</div>
);
};
export default MainMaps;
