use-places-autocomplete icon indicating copy to clipboard operation
use-places-autocomplete copied to clipboard

difficulty with requestOptions

Open Minte-grace opened this issue 3 years ago • 15 comments

can anyone help with the correct way of passing location and radius to requestOptions I tried usePlacesAutocomplete({ requestOptions: { types: "address", radius: 500, location: { lat: 8.7, 38.8 } }, debounce: 300, }); but its not working

Minte-grace avatar Dec 22 '21 12:12 Minte-grace

Same problem.

gitmazzio avatar Jan 17 '22 15:01 gitmazzio

@Minte-grace Seems you lack the location.lng property?

usePlacesAutocomplete({
      requestOptions: {
        types: "address",
        radius: 500,
        location: {
          lat: 8.7,
+         lng: 38.8,
        },
      },
      debounce: 300,
    });

wellyshen avatar Jan 23 '22 10:01 wellyshen

@wellyshen yeah but the thing is, it aliases the suggestion but it doesn't strict to that location. I end up calling the places on the server-side and fetch the detail of the places using this library

Minte-grace avatar Jan 24 '22 16:01 Minte-grace

what is not working?

johnhaup avatar Feb 21 '22 04:02 johnhaup

I'm also running into issues when trying to provide a the location option. By providing a location request option using the example in the README (https://github.com/wellyshen/use-places-autocomplete#create-the-component), autocomplete does not work. Typing into the input field does not successfully get any suggestions. If I remove location, however, things work again.

const {
    ready,
    value,
    suggestions: { status, data },
    setValue
  } = usePlacesAutocomplete({
    requestOptions: {
      location: { lat: 40.7127753, lng: -74.0059728 } // Having this causes autocomplete to not work
    }
  });

Oddly not seeing anything out of the ordinary in the console and logging status prints an empty string and never OK.

mduong avatar Mar 24 '22 03:03 mduong

Try also specifying a radius in the requestOptions. The location bias is defined as a circle with location as the center and radius in meters (max 50,000 meters).

wangela avatar Mar 25 '22 06:03 wangela

Try also specifying a radius in the requestOptions. The location bias is defined as a circle with location as the center and radius in meters (max 50,000 meters).

Ah yeah, I did try that as well but no luck.

mduong avatar Mar 25 '22 16:03 mduong

I'm also running into issues when trying to provide a the location option. By providing a location request option using the example in the README (https://github.com/wellyshen/use-places-autocomplete#create-the-component), autocomplete does not work. Typing into the input field does not successfully get any suggestions. If I remove location, however, things work again.

const {
    ready,
    value,
    suggestions: { status, data },
    setValue
  } = usePlacesAutocomplete({
    requestOptions: {
      location: { lat: 40.7127753, lng: -74.0059728 } // Having this causes autocomplete to not work
    }
  });

Oddly not seeing anything out of the ordinary in the console and logging status prints an empty string and never OK.

I had the same issue, but adding radius fixed it. Perhaps try clearing site data after adding radius? ... The library uses session storage for caching, so it might be causing an issue somehow.

image

Also, I've upgraded to v2.0.0, not sure if it makes a difference. And also, you may want to clear the site data after doing so.

(P.S: Make sure to clear the site data for localhost:3000 only. I once cleared site data for all websites by mistake or something, logging me out of all my accounts)

hossameldeen avatar Mar 30 '22 07:03 hossameldeen

Thanks @hossameldeen. Unfortunately, that also didn't work for me. I was only able to get it to work by passing an instance of LatLng like so:

const {
    ready,
    value,
    suggestions: { status, data },
    setValue
  } = usePlacesAutocomplete({
    requestOptions: {
      location: new window.google.maps.LatLng(40.7127753, -74.0059728),
      radius: 5000,
    }
  });

mduong avatar Mar 30 '22 23:03 mduong

When debugging the issue, I've found that loading remains true in case of an invalid input like missing radius or sending in a wrong type for location. My suspicion is that getPlacePredictions throws an error instead of calling the callback. In that case, loading remains true and we don't propagate the error to the library's user.

Here, we set loading: true:

https://github.com/wellyshen/use-places-autocomplete/blob/c9423dc299f08aef9380c9f14901f64bf5d9f040/src/usePlacesAutocomplete.ts#L105

If getPlacesPrediction throws an error instead of calling the callback in case of an invalid input, loading will remain true, and the library's user won't know that an issue has happened:

https://github.com/wellyshen/use-places-autocomplete/blob/c9423dc299f08aef9380c9f14901f64bf5d9f040/src/usePlacesAutocomplete.ts#L137-L155

A possible enhancement would be to try/catch the call getPlacesPrediction call and add the error to suggestions state somehow.

For now, if someone is facing a similar problem: console.log(loading). And if it remains true, the issue is probably that your arguments are invalid somehow. You can the review parameter types & constraints here.

hossameldeen avatar Mar 31 '22 06:03 hossameldeen

@hossameldeen That's wired, the callback supposes should be triggered even if there's an error because the callback is given a status argument. 🤔

wellyshen avatar Mar 31 '22 14:03 wellyshen

Summary: Strangely, when calling getPlacesPredictions in callback style with an invalid input, neither an error is thrown nor is the callback called. However, when using the Promise-based variant, we indeed receive an error in catch.

Original message:

@wellyshen Agreed, it's weird indeed.

  1. Take this even weirder info: It neither calls the callback nor throws an error in case of an input error 🤔 Nothing is logged for this code:
const service = new google.maps.places.AutocompleteService();
    try {
      service.getPlacePredictions(
        {
          input: "restaurant",
          types: ["establishment"],
          location: new google.maps.LatLng({
            lat: 50,
            lng: 50,
          }),
          // radius: 123,
        },
        (predictions, status) => {
          console.log("In callback", predictions, status);
        }
      );
    } catch (e) {
      console.log("In catch", e);
    }
  1. However, there's hope: When using Promise-based calling, it does call catch. Code:
    service
      .getPlacePredictions({
        input: "restaurant",
        types: ["establishment"],
        location: new google.maps.LatLng({
          lat: 50,
          lng: 50,
        }),
        // radius: 123,
      })
      ?.then((predictions) => {
        console.log("In then", predictions);
      })
      .catch((e) => {
        console.log("In catch", e);
      });

Logs: image

Update: Removed the point about status representing server errors only. The reference screenshot had "INVALID_REQUEST" as one of the possible values, actually.

hossameldeen avatar Mar 31 '22 18:03 hossameldeen

@hossameldeen Thank you for the detailed explanation. There's room for improving the error handling. Will spend time thinking about it. BTW, a PR for the error handling improvement is welcome as well.

wellyshen avatar Apr 03 '22 09:04 wellyshen

Thanks @hossameldeen. Unfortunately, that also didn't work for me. I was only able to get it to work by passing an instance of LatLng like so:

const {
    ready,
    value,
    suggestions: { status, data },
    setValue
  } = usePlacesAutocomplete({
    requestOptions: {
      location: new window.google.maps.LatLng(40.7127753, -74.0059728),
      radius: 5000,
    }
  });

I'm using NextJS, load the script by next/script

<Script strategy="beforeInteractive" src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" />

I got ReferenceError: google is not defined

cdslxc avatar May 20 '22 18:05 cdslxc

Thanks @hossameldeen. Unfortunately, that also didn't work for me. I was only able to get it to work by passing an instance of LatLng like so:

const {
    ready,
    value,
    suggestions: { status, data },
    setValue
  } = usePlacesAutocomplete({
    requestOptions: {
      location: new window.google.maps.LatLng(40.7127753, -74.0059728),
      radius: 5000,
    }
  });

I'm using NextJS, load the script by next/script

<Script strategy="beforeInteractive" src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" />

I got ReferenceError: google is not defined

That is probably because you have not waited to the api to load and tried to read google before it has ended.

Also for those of you having problems, yes, as mentioned, the hook uses cache by default, so you might need to delete sessionstorage when you change the requestoptions (this could maybe be automatic somehow).

Lastly, radius and location are deprecated now, so for someone wondering how it should be done now, an option could be using a circle with a radius and using locationBias like so:

requestOptions: {
      locationBias: new google.maps.Circle({ {lat: 40.71960243832271, lng: -74.03454420585065}, 
      radius: 1000
 }

MarioPerezDev avatar May 19 '23 19:05 MarioPerezDev