Take Geolocation Coordinates (Reactjs)

Asked

Viewed 1,641 times

1

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

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

        }                           

    }


},

...

1 answer

2


That function success is asynchronous. Uses the this.setState using .bind or passing the this by reference thus:

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
            }
          });
  • 2

    It worked perfectly! Thank you!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.