I'm using the react-geocode api to get coordinates from a string address (like 1234 home street, etc.). So far, this is my code.
async function ConvertAddress(address) {
if (address !== "") {
Geocode.fromAddress(address, resolve).then(
(response) => {
const { lat, lng } = response.results[0].geometry.location;
const center = { lat: lat, lng: lng}; // if I console logged center from here, it would work fine.
return center;
},
(error) => {
alert("ConvertAddress error:", error);
}
);
}
}
However, I'm not sure how to access "center" from outside this function (such as from another function). I've tried this:
console.log("ConvertAddress test", ConvertAddress(data[0]));
And it returns this:
ConvertAddress test
Promise { <state>: "fulfilled", <value>: undefined }
<state>: "fulfilled"
<value>: undefined
<prototype>: Promise.prototype { … }
Can I have some help with returning center in such a way that I can call it without it being undefined? Thanks in advance.
Try this
async function ConvertAddress(address) {
if (address !== "") {
var addressResult = await Geocode.fromAddress(address, resolve).then(
(response) => {
const { lat, lng } = response.results[0].geometry.location;
const center = { lat: lat, lng: lng}; // if I console logged center from here, it would work fine.
return center;
},
(error) => {
return "error in results"
}
);
addressResult.then(function(result){
console.log(result);
})
}
}