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.
This worked for me:
async function coordinateGenerator(address) {
if (address !== "") {
return new Promise(function(resolve, reject) {
Geocode.fromAddress(address).then(
(response) => {
const { lat, lng } = response.results[0].geometry.location;
resolve([lat, lng]);
},
(error) => {
alert(error);
reject("Request failed");
}
);
})
}
}
Then call it with:
const center = await coordinateGenerator(a);