1

can anyone help me or give me solution to get value of

"position.coords.latitude"

i want that value update this.state "city" after user click button

class Home extends Component{

constructor(props){
    super(props)
    this.state = {
        city: '',
        lats : '',
        long : ''
    }
    this.Kirim = this.Kirim.bind(this)
}

Kirim() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(Position){
            this.setState({ city:position.coords.latitude}) // erorr here
        })

      } else { 

      } 
}

render(){
    let {city} = this.state
    console.log(city)
    return(

        <Fragment>
            <div className="form-add">
                <button onClick={this.Kirim}>Kirim</button>
            </div>
        </Fragment>

    )
}

}

2 Answers2

1

You should use an arrow function () => {} instead of regular function.

When using function, this will be the function's this.

When using arrow function, it will be the component's this, which has setState.

Change

// normal function
navigator.geolocation.getCurrentPosition(function(Position) {
    this.setState({ city:position.coords.latitude}) // error here
})

to

// arrow function 
navigator.geolocation.getCurrentPosition(position => {
      this.setState({ city:position.coords.latitude}) // error here
})
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
0

Change onClick={this.Kirim} to "onClick={() => this.Kirim()}, and position.coords.latitude to Position.coords.latitude. From where do you get navigator?

Iiskaandar
  • 394
  • 2
  • 7