I'm connecting a custom location api to google maps. On each locations longLat property I am calling a function calculateDistances to get the arguments needed for a Google Distance Matrix API call.
Here is where that call is happening:
{Object.keys(this.state.locations).map((i) => {
let locale = this.state.locations[i];
return <Location name={locale.name}
address={locale.address}
longLat={locale.longLat}
needsCode={locale.needsCode}
needsKey={locale.needsKey}
distances={this.calculateDistances(locale.longLat)}
handicapAccess={locale.handicapAccess}
code={locale.code}
id={locale.id} />
})},
The actual Google Distance Matrix API call is then nested within the calculateDistances function. Within this nested function I set the distance that is returned from the call as a variable: 'dist'.
calculateDistances(longLat) {
const origins = [Object.values(this.state.currentLocation).join()];
const destinations = [Object.values(longLat).join()];
const travelMode = this.state.travelMode.length ? this.state.travelMode : 'WALKING';
distance.matrix(origins, destinations, travelMode, (err, distances) => {
let dist = distances.rows[0].elements[0].distance.text;
})
return dist;
}
This is working great and within the nested function dist is being defined correctly. However, I cannot get the dist variable to return from the whole calculateDistances function.
So... distance.matrix is making the api call (google-distance-matrix is imported as distance at the top of the component) and getting the dist variable set correctly.
How do I get dist to be returned by the overall calculateDistances function? As of right now it is returning undefined.