我正在嘗試將地圖置于地理位置中心,但出現以下錯誤:
未捕獲的型別錯誤:無法讀取未定義的屬性(讀取“坐標”)
如果我在 getLocationHandler 中控制臺記錄位置,則該物件似乎具有坐標。
import GoogleMapReact from "google-map-react";
import { Geolocation } from "@ionic-native/geolocation";
import { IonLoading } from "@ionic/react";
const Map = (props) => {
const [isLoading, setIsLoading] = useState(false);
const [position, setPosition] = useState();
const getLocationHandler = async () => {
try {
setIsLoading(true);
const position = await Geolocation.getCurrentPosition();
setPosition(position);
} catch (e) {}
setIsLoading(false);
};
useEffect(() => {
getLocationHandler();
}, []);
return (
<>
<IonLoading
isOpen={isLoading}
message={"Getting Location..."}
onDidDismiss={() => setIsLoading(false)}
></IonLoading>
<div className="map">
<div className="google-map" style={{ height: "100vh", width: "100%" }}>
<GoogleMapReact
bootstrapURLKeys={{ key: .... }}
defaultCenter={
{
lat: position.coords.latitude,
lng: position.coords.longitude,
}
}
defaultZoom={11}>
</GoogleMapReact>
</div>
</div>
</>
);
};
export default Map;
uj5u.com熱心網友回復:
在您的第一次渲染中,position將是未定義的,因此當您嘗試使用position.coords.latitude它時會拋出該錯誤。我可能會利用您的isLoading狀態,并且僅在該狀態為假時才渲染組件的第二部分-
<div className="google-map" style={{ height: "100vh", width: "100%" }}>
{!isLoading && (
<GoogleMapReact
...etc
)}
</div>
isLoading此外,將初始值設定為 true 而不是在異步加載函式中手動將其設定為 true可能是有意義的。
或者,isLoading您可以直接檢查,而不是檢查position?.coords?.latitude
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/452980.html
