How to get location information in react?
Asked Answered
S

2

6

I want to get location information by using Geolocation API in react.

I made a button to get location info in this code.

import React, { Component } from 'react'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      latitude: null,
      longitude: null,
    }
  }

  position = async () => {
    await navigator.geolocation.getCurrentPosition(
      position => this.setState({ 
        latitude: position.coords.latitude, 
        longitude: position.coords.longitude
      }), 
      err => console.log(err)
    );
    console.log(this.state.latitude)
  }

  render() {
    return (
      <div>
        <button onClick={this.position} className='Filter'>Filter</button>
      </div>
    );
  }
}

export default App;

Once I pressed a button, console shows null. However, when I pressed a button again, the console shows location info.

Do you have any idea why I couldn't get the location info for the first time?

Semitone answered 21/4, 2019 at 7:21 Comment(4)
try console.log inside the render not in that functionSlander
It will still give a null and not update the component.Altostratus
setState has a second argument, a callback , that is triggered after state is set, so put console.log inside it like .setState({...}, function(){console.log(this.state.latitude)});Garment
@HabeebRahman Thank you for your comment. that worked !Semitone
O
12

setState is an asynchronous function.

When you call position the first time, the state is eventually updated. The second time it is already there, which is why it gets logged.

You can move the logging to the second parameter of setState, which is a callback.

this.setState({ 
    latitude: position.coords.latitude, 
    longitude: position.coords.longitude
  }, newState => console.log(newState))
Ossetia answered 21/4, 2019 at 7:28 Comment(2)
Thank you for your comment. I put setState in componentWillMount, and I could solve it!!Semitone
@Semitone You could just await the setState call, assuming you declare the getCurrentPosition callback as async.Flank
S
0
position = () => {
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(function (position) {
            console.log('latitude >>>>>>>>', position.coords.latitude);
            console.log('longitude >>>>>>>>', position.coords.longitude);
        });
    }
};

The watchPosition method tracks the device's position continuously. Whenever the position changes, the provided callback function is called with an updated position object. This object contains latitude and longitude, among other location data.

Straddle answered 3/11 at 5:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.