问题
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}
回答1:
I don't know how to achieve this using the Geolocate control... but an alternative would be to just use the user's device location & plain javascript to fetch the current location... I.E. Something like this:
useEffect(() => {
navigator.geolocation.getCurrentPosition(pos => {
setViewport({
...viewport,
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
});
});
}, []);
Hope this helps someone!
来源:https://stackoverflow.com/questions/57617959/how-can-i-get-the-location-of-the-user-using-at-react-map-gl