reactjs - How can i get the location of the user - Using at React Map GL
问题描述
I'm using React Map GL, and I want to put the latitude and longitude of the user
Returning the component like this:
export default geolocated({
positionOptions: {
enableHighAccuracy: false
},
userDecisionTimeout: 5000
})(Layout);
I'm tried to use react-geolocated but it's returning null coords.
I want to get these informations when the component mounts, that's the code:
componentDidMount() {
console.log(this.props);
if (navigator.geolocation) {
const viewport = {
...this.state.viewport,
latitude: this.props.coords.latitude,
longitude: this.props.coords.longitude
};
this.setState({ viewport });
}
}
The map component:
<MapGL
{...viewport}
//onClick={this.handleMapClick}
mapStyle="mapbox://styles/mapbox/streets-v9"
mapboxApiAccessToken={TOKEN}
perspectiveEnabled
onViewportChange={viewport => this.setState({ viewport })}
>
<div className="geo" style={geolocateStyle}>
{" "}
<GeolocateControl
positionOptions={{ enableHighAccuracy: true }}
trackUserLocation={true}
/>
</div>
<div className="nav" style={navStyle}>
<NavigationControl
onViewportChange={viewport => this.setState({ viewport })}
/>
</div>
</MapGL>
I'm getting the props like this:
{coords: null, isGeolocationAvailable: true, isGeolocationEnabled: true, positionError: null}
解决方案
我不知道如何使用 Geolocate 控件来实现这一点......但另一种方法是只使用用户的设备位置和纯 javascript 来获取当前位置...... IE 像这样的东西:
useEffect(() => {
navigator.geolocation.getCurrentPosition(pos => {
setViewport({
...viewport,
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
});
});
}, []);
希望这对某人有帮助!
推荐阅读
- html - 离子输入类型编号允许离子形式的点
- python - Why I am getting None in place of int from if block inside a method called by another method in the class
- swiftui - 如何在 swiftUI 中创建循环的心跳动画?
- ubuntu-18.04 - h5dump 失败并显示“libhdf5_serial.so.100:无法打开共享对象文件”
- python - 函数是python中内置类“函数”的实例吗?
- cypress - 使用 cypress 运行测试时如何访问新窗口
- python - 我是否仅限于在 kivy 中对每个屏幕进行硬编码?
- java - 在 Tomcat7 中成功运行,但在 centOS 中的 tomcat9 中出现错误
- seaborn - 如何为 seaborn.histplot() 使用 kde_kws 参数?
- sql - 通过内部窗口功能排序如何工作?