react-geocode icon indicating copy to clipboard operation
react-geocode copied to clipboard

Need to add this to JS function

Open rananaresh86 opened this issue 5 years ago • 5 comments
trafficstars

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

rananaresh86 avatar Oct 14 '20 23:10 rananaresh86

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);
}

shukerullah avatar Oct 15 '20 09:10 shukerullah

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? Screenshot at Oct 20 15-53-51

Thanks

rananaresh86 avatar Oct 20 '20 10:10 rananaresh86

@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.

ziyaddin avatar Nov 02 '20 13:11 ziyaddin

@rananaresh86 any success?

ziyaddin avatar Dec 08 '20 08:12 ziyaddin

Hi @shukerullah ,

Did not get deep into it actually. But the issue is still there.

Thanks

rananaresh86 avatar Dec 08 '20 11:12 rananaresh86

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;
};

shukerullah avatar Sep 19 '23 17:09 shukerullah