Matthew Poletiek Matthew Poletiek - 2 months ago 10
Javascript Question

using navigator geolocation with reactors [resolved]

I'm trying to display geolocation variables

position.coords.lat/long
and I'm having trouble storing the values in a global scope. Here is the code:

var GeoLoco = React.createClass({
lat: 0,
long: 0,
handler: function(position) {
this.lat = position.coords.latitude;
this.long = position.coords.longitude;
console.log("Lat,Long: "+this.lat+","+this.long);
},
render: function() {
navigator.geolocation.getCurrentPosition(this.handler);
return <p>Lat,Long: {this.lat},{this.long}</p>;
}
});


console.log
displays the location data, but
this.lat
and
this.long
render as 0

Answer

Even if your variable's values changed, you have to re-render your component to update what you're seeing. The component's state does it for you.

More information here

By default, when your component's state or props change, your component will re-render.

So :

var GeoLoco = React.createClass({
  getInitialState: function() {
    return {lat: 0, long: 0};
  },
  handler: function(position) {
    this.setState({
      lat: position.coords.latitude,
      long: position.coords.longitude
    });
  },
  render: function() {
    // If this.state.lat is not equal to 0, do not call again getCurrentPosition()
    if (!this.state.lat)
      navigator.geolocation.getCurrentPosition(this.handler);
    return <p>Lat,Long: {this.state.lat},{this.state.long}</p>;
  }
});

If you don't want to use state, you can call forceUpdate() at the end of your handler method.

handler: function(position) {
  this.lat = position.coords.latitude;
  this.long = position.coords.longitude;
  console.log("Lat,Long: "+this.lat+","+this.long);
  this.forceUpdate();
},