shukerullah / react-geocode

A React module to transform a description of a location (i.e. street address, town name, etc.) into geographic coordinates (i.e. latitude and longitude) and vice versa.
MIT License
207 stars 33 forks source link

Need to add this to JS function #38

Closed rananaresh86 closed 11 months ago

rananaresh86 commented 3 years ago

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

shukerullah commented 3 years ago

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);
}
rananaresh86 commented 3 years ago

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

ziyaddin commented 3 years ago

@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 commented 3 years ago

@rananaresh86 any success?

rananaresh86 commented 3 years ago

Hi @shukerullah ,

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

Thanks

shukerullah commented 11 months ago

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