![](/img/trans.png)
[英]How do I pass origin and destination co-ordinates to the Google Maps directions API?
[英]How do I get Geolocation API co-ordinates out of my nested function and into React state?
當用戶單擊按鈕時,我正在嘗試使用Geolocation API獲取用戶的位置:
<button onClick={this.setNewLatLong()}>"Use my location"</button>;
我可以使用以下代碼訪問緯度/經度坐標:
setNewLatLong = () => {
navigator.geolocation.getCurrentPosition(displayLocationInfo);
function displayLocationInfo(position) {
const longitude = position.coords.longitude;
const latitude = position.coords.latitude;
console.log(`long: ${longitude} | lat: ${latitude}`);
}
}
但是我無法將數據輸入到我的 state 中,因為latitude
和longitude
變量在函數中嵌套得太多了。
如何將這些數據輸入到我的 state 中?
在 React 中,您保留組件的 state 中的信息。 您可以像這樣設置 state:
this.setState({
lon: longitude,
lat: latitude
})
並從您的視圖(渲染功能)或您可能需要的任何其他地方訪問 state。
React 中的每個組件 state 更新都應該使用setState()
來完成。 對於您的情況,您可以在傳遞給getCurrentPosition()
的回調 function 中使用setState()
) 。
navigator.geolocation.getCurrentPosition(position => {
this.setState({
lat: position.coords.latitude,
lng: position.coords.longitude
});
})
我還建議考慮對 state 使用React 鈎子(在您學習完 React 的基礎知識之后)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.