My asynchronous function does not return the value where it is called, but within its scope is working right. Reactjs + google maps

Asked

Viewed 40 times

0

import React, { Component } from "react";
import { Map, GoogleApiWrapper, Marker } from "google-maps-react";
import { MAPS_API_TOKEN, GEOCODE_API_TOKEN } from 
"../Enviroments/dev";
import Geocode from "react-geocode";

const mapStyles = {
width: "100%",
height: "100%"
};

var labelIndex = 0;
// var description = "Pão";

function getLabelIndex() {
labelIndex++;
return labelIndex.toString();
}

Geocode.setApiKey(GEOCODE_API_TOKEN);

class SimpleMap extends Component {
constructor(props) {
super(props);
this.state = {
  resultado: ""
};

this.getDetail = this.getDetail.bind(this);
}

getMarkers() {
if (typeof this.props.locations !== "undefined") {
  return this.props.locations.map(location => (
    <Marker
      title={this.getDetail(location)}
      label={getLabelIndex()}
      key={location.time}
      position={{
        lat: location.latitude,
        lng: location.longitude
      }}
    />
  ));
}
}

getDetail(location) {
this.getDescription(location).then(result => {
  console.log(result);
  return result;
});
}

getDescription(location) {
 var address = "Não foi possível carregar o endereço";

 Geocode.fromLatLng(location.latitude, location.longitude).then(
  status, response => {
    if(status === 'OK')
    address = response.results[0].formatted_address;
  }
);

const formatedTime = this.getFormatedTime(location.time);

const description =
  "Data: " +
  formatedTime.date +
  "\nHora: " +
  formatedTime.horary +
  "\nEndereço: " +
  address;

return description;

}

getFormatedTime(time) {
const yyyy = time.slice(0, 4);
const MM = time.slice(4, 6);
const dd = time.slice(6, 8);

const hh = time.slice(8, 10);
const mm = time.slice(10, 12);
const ss = time.slice(12, 14);

const formatedTime = {
  horary: hh + ":" + mm + ":" + ss,
  date: dd + "/" + MM + "/" + yyyy
};

return formatedTime;
}

  render() {
return (
  <div>
    <Map
      google={this.props.google}
      zoom={8}
      style={mapStyles}
      initialCenter={this.props.zoom_position}
      center={this.props.zoom_position}
    >
      {(labelIndex = 0)}
      {this.getMarkers()}
    </Map>
  </div>
);
}
}

export default GoogleApiWrapper({
apiKey: MAPS_API_TOKEN
})(SimpleMap);

inserir a descrição da imagem aqui

value inside the getDetail function is ok, but where I call it and pass the data, it n shows the value when passing the mouse over the marker. What can be the mistake?

  • 1

    There are a lot of things wrong with this code. First you don’t use then when you use await, it becomes irrelevant. Then you need to have a state, because as it is manipulating many countries it is good that you have a render when the value is changed.So put your entire code, so that we can help. And lastly avoid using var.

  • I put all the code, as you requested

  • had put a state to receive the result in getDetail, but whenever I passed the same, fall into a loop

1 answer

0

Basically I changed the following, the function getDescription will return the result inside a callback function passed to it. This will return in getDetail which will take the description and insert into the state, I created an object array called results. Within this array an object with values will be received location and detail(description). This way the render will be done. In order not to be called several times as you mentioned from the loop, I added inside the IdMount. And getMarkers instead of making a map in the props, I just make a map in the array that is in the state I just created. I found this method getLabelIndex very strange... It seems like a gambiarra, so instead of having a global variable being incremented, I just used the index of the map function

import React, { Component } from "react";
import { Map, GoogleApiWrapper, Marker } from "google-maps-react";
import { MAPS_API_TOKEN, GEOCODE_API_TOKEN } from 
"../Enviroments/dev";
import Geocode from "react-geocode";

const mapStyles = {
  width: "100%",
  height: "100%"
};

Geocode.setApiKey(GEOCODE_API_TOKEN);

class SimpleMap extends Component {

  constructor(props) {
    super(props);
    this.state = {
      resultados: []
    };

    this.getDetail = this.getDetail.bind(this);
  }

  componentDidMount(){
    this.props.locations.map(location => (
        this.getDetail(location)
      )
    );
  }

  getMarkers() {
    if (this.state.resultados.length > 0) {
      return this.state.resultados.map((resultado,index) => (
        <Marker
          title={resultado.detail}
          label={index.toString()}
          key={resultado.location.time}
          position={{
            lat: resultado.location.latitude,
            lng: resultado.location.longitude
          }}
        />
      ));
    }
  }

  getDetail(location) {
    this.getDescription(location, (description) => {
      this.setState(state => {
        const resultado = state.resultados.concat({
          location: location,
          detail: description
        })

        return {
          resultados: resultado
        }
      })
    })
  }

  getDescription(location, callback) {
    Geocode.fromLatLng(location.latitude, location.longitude).then(
      status, response => {
        if(status === 'OK'){
          const address = response.results[0].formatted_address || "Não foi possível carregar o endereço";
          const formatedTime = this.getFormatedTime(location.time);
          const description =
            "Data: " +
            formatedTime.date +
            "\nHora: " +
            formatedTime.horary +
            "\nEndereço: " +
            address;

          callback(description);
        }
      }
    );
  }

  getFormatedTime(time) {
    const yyyy = time.slice(0, 4);
    const MM = time.slice(4, 6);
    const dd = time.slice(6, 8);

    const hh = time.slice(8, 10);
    const mm = time.slice(10, 12);
    const ss = time.slice(12, 14);

    const formatedTime = {
      horary: hh + ":" + mm + ":" + ss,
      date: dd + "/" + MM + "/" + yyyy
    };

    return formatedTime;
  }

  render() {
    return (
      <div>
        <Map
          google={this.props.google}
          zoom={8}
          style={mapStyles}
          initialCenter={this.props.zoom_position}
          center={this.props.zoom_position}
        >
          {this.getMarkers()}
        </Map>
      </div>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: MAPS_API_TOKEN
})(SimpleMap);

Browser other questions tagged

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