gnxvw
gnxvw

Reputation: 454

How to get location information in react?

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?

Upvotes: 6

Views: 40277

Answers (2)

Santhosh
Santhosh

Reputation: 1

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.

Upvotes: 0

Kraylog
Kraylog

Reputation: 7553

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))

Upvotes: 12

Related Questions