Get Geolocation Coordinates (Reactjs)

1

Hello, I'm developing a simple application that takes the geographical coordinates of google maps api. It's working, but I'm not getting the values that are in the other function. In fact I just want a way to get the Latitude and Longitude values into the mapCoordinates object.

var App = React.createClass({



getInitialState(){


    GMaps.geolocate({
    success: function(position) {

        //alert("Latitude: " + position.coords.latitude + 
        //"<br>Longitude: " + position.coords.longitude); //dessa
//forma funciona porém quero pegar os valores de Latitude e Longitude //no return


        var userLat = position.coords.latitude;
        var userLng = position.coords.longitude;    

    },
    error: function(error) {
        alert('Geolocation failed: '+error.message);
    },
    not_supported: function() {
        alert("Your browser does not support geolocation");
    },
    always: function() {
        //alert("Done!");
    },

    });

    return {

        mapCoordinates: {

            //lat: userLat, //aqui que devo obter o valor de userLat 
            //lng: userLng //aqui que devo obert o valor de userLng

        }                           

    }


},

...
    
asked by anonymous 26.06.2016 / 03:12

1 answer

2

This success function is asynchronous. Uses this.setState using .bind or passing this by reference like this:

var App = React.createClass({
  getInitialState() {

      // Extract the favorite locations from local storage

      var favorites = [];
      var self = this;

      if (localStorage.favorites) {
        favorites = JSON.parse(localStorage.favorites);
      }

      GMaps.geolocate({
        success: function(position) {
          var userLat = position.coords.latitude;
          var userLng = position.coords.longitude;
          self.setState({
            mapCoordinates: {
              lat: userLat,
              lng: userLng
            }
          });
    
26.06.2016 / 09:53