react-geocode
react-geocode copied to clipboard
Need to add this to JS function
Hi @shukerullah ,
Thanks for this great package. Can you please help me how to add this code into a function which will take address as argument and return an object of lat long? I am tried as below
function geoCodeAddressToCoordinates(address) {
let dataObj = {};
Geocode.fromAddress(address).then(
response => {
const {lat, lng} = response.results[0].geometry.location;
// console.log(lat, lng);
dataObj = {
latitude: lat,
longitude: lng,
};
return dataObj;
},
error => {
console.error(error);
}
);
}
var results = geoCodeAddressToCoordinates("Denver United States");
console.log(results);
It looks like return executed first before we got the api response. Please suggest.
Thanks
You cannot return like that. Either use async or callback.
// using async
async getCoordinates() {
const response = await Geocode.fromAddress('Denver United States');
const {lat, lng} = response.results[0].geometry.location;
const dataObj = {
latitude: lat,
longitude: lng,
};
console.log(dataObj);
}
Hi @shukerullah ,
Thanks it works. Can you please let me know how I can prevent the console error as attached in screenshot when we search some invalid address?

Thanks
@rananaresh86 As can be seen from the image, you have an uncaught error. So, you need to catch the error, in other words, you need to add error handling for your address search function.
@rananaresh86 any success?
Hi @shukerullah ,
Did not get deep into it actually. But the issue is still there.
Thanks
Hi @rananaresh86, This issue seems to be inactive. If you encounter this problem again or have further questions, please feel free to open a new issue. We're here to help!
import {
setKey,
fromAddress
} from 'react-geocode';
const getCoordinates = async () => {
let coords = {
latitude: undefined,
longitude: undefined,
};
const response = await fromAddress('Denver United States');
if (response && response.results) {
const {lat, lng} = response.results[0].geometry.location;
coords = {
latitude: lat,
longitude: lng,
};
}
return coords;
};