Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

281
Vistas
I am not able to store the returned value of a javaScript function (of Geocoding) in a variable

I am trying to store the latitude and longitude values I calculated inside the function. If I console.log both the values inside the function, it is working fine. However, if I return those values to use them somewhere else, then I cannot do so (it throws an error in the console as having this coordinates list as undefined). Whatever I am returning from this Geocoding function, it shows undefined in the console. Here is the code snippet:

function Geocoding() {
  axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
    params: {
      address: enteredAddress,
      key: 'my API key here'
    }
  })
    .then(function (response) {
      var lat = response.data.results[0].geometry.location.lat;
      var lng = response.data.results[0].geometry.location.lng;
      return [lat, lng];
    })

    .catch(function (error) {
      console.log(error);
    });
}

const submitHandler = (event) => {
  event.preventDefault();

  var coordinates = Geocoding();

  const userInput = { //object
    location: {
      latitude: coordinates[0],
      longitude: coordinates[1],
      maxDistance: enteredDistance
    },
    instrumentType: enteredInstrumentType,
    awardNumber: enteredAwardNumber,
    includeRetired: enteredIRI
  };
  props.onSaveUserInput(userInput);

  setEnteredAddress('');
  setEnteredDistance('');
  setEnteredInstrumentType('');
  setEnteredAwardNumber('');
  setEnteredIRI('');
};
about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

The problem is that the Geocoding is not returning anything. Anyway, I'd convert the code to async/await if possible so it's easier to comprehend. Take a look below at the same code fixed with async/await.

async function Geocoding() {
  try {
    const response = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
      params: {
        address: enteredAddress,
        key: 'my API key here'
      }
    })
    
    var lat = response.data.results[0].geometry.location.lat;
    var lng = response.data.results[0].geometry.location.lng;
    return [lat, lng];
  } catch (error) {
    console.error(error)
    throw error;
  }
}

const submitHandler = async (event) => {
  event.preventDefault();

  var coordinates = await Geocoding();

  const userInput = { //object
    location: {
      latitude: coordinates[0],
      longitude: coordinates[1],
      maxDistance: enteredDistance
    },
    instrumentType: enteredInstrumentType,
    awardNumber: enteredAwardNumber,
    includeRetired: enteredIRI
  };
  props.onSaveUserInput(userInput);

  setEnteredAddress('');
  setEnteredDistance('');
  setEnteredInstrumentType('');
  setEnteredAwardNumber('');
  setEnteredIRI('');
};

Notice that to call Geocoding you need to use also async/await or use the Promise.then like Geocoding().then((coordinates) => {...})

about 4 years ago · Santiago Gelvez Denunciar

0

Your Geocoding does not return variables. It just calls another function.

function Geocoding() {
    axios.get().then().catch();
}

The get/then/catch functions return a Promise. You can return the Promise.

function Geocoding() {
    return axios.get().then().catch();
}

You can get the variable by calling then.

const submitHandler = event => {
  event.preventDefault();

  Geocoding().then(coordinates => {
    const userInput = {
    // ...
    setEnteredIRI("");
  });
};

By the way, if there is an error, you catch it in the Geocoding function, and return nothing in the catch. The coordinates in Geocoding().then(coordinates => {}) will be undefined.

You can change it:

function Geocoding() {
  return axios
    .get("https://maps.googleapis.com/maps/api/geocode/json", {
      params: {
        address: enteredAddress,
        key: "my API key here",
      },
    })
    .then(function (response) {
      var lat = response.data.results[0].geometry.location.lat;
      var lng = response.data.results[0].geometry.location.lng;
      return [lat, lng];
    });
}

const submitHandler = event => {
  event.preventDefault();

  Geocoding()
    .then(coordinates => {
      const userInput = {
        //object
        location: {
          latitude: coordinates[0],
          longitude: coordinates[1],
          maxDistance: enteredDistance,
        },
        instrumentType: enteredInstrumentType,
        awardNumber: enteredAwardNumber,
        includeRetired: enteredIRI,
      };
      props.onSaveUserInput(userInput);

      setEnteredAddress("");
      setEnteredDistance("");
      setEnteredInstrumentType("");
      setEnteredAwardNumber("");
      setEnteredIRI("");
    })
    .catch(function (error) {
      console.log(error);
    });
};

If you like async/await

async function Geocoding() {
  const response = await axios.get(
    "https://maps.googleapis.com/maps/api/geocode/json",
    {
      params: {
        address: enteredAddress,
        key: "my API key here",
      },
    }
  );
  const lat = response.data.results[0].geometry.location.lat;
  const lng = response.data.results[0].geometry.location.lng;
  // or
  // const { lat, lng } = response.data.results[0].geometry.location;
  return [lat, lng];
}

const submitHandler = async event => {
  event.preventDefault();

  try {
    const coordinates = await Geocoding();
    const userInput = {
      //object
      location: {
        latitude: coordinates[0],
        longitude: coordinates[1],
        maxDistance: enteredDistance,
      },
      instrumentType: enteredInstrumentType,
      awardNumber: enteredAwardNumber,
      includeRetired: enteredIRI,
    };
    props.onSaveUserInput(userInput);

    setEnteredAddress("");
    setEnteredDistance("");
    setEnteredInstrumentType("");
    setEnteredAwardNumber("");
    setEnteredIRI("");
  } catch (error) {
    console.log(error);
  }
};
about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda