Search code examples
google-mapsgoogle-places-apigoogle-places-autocompletegoogle-maps-autocomplete

How do I get a sessiontoken from google place autocomplete API if I am working with the web service?


Before I was using the Javascript widged from google autocomplete place and fine, it worked and there's a function so you get the sessionToken and you save some $$ in billing, but my PM wanted me to work using request to https://maps.googleapis.com/maps/api/place/autocomplete/json?parameters and I cannot find any info or documentation on how to get these tokens using the API. Even in the google video they mention the possibility of use the web service and use sessiontokens, but now, how do you make those?

I tried using the Javascript widget but that's not what the PM wants


Solution

  • So what I found out was that even when the Javascript widget of Place Autocomplete brings a function itself to create the sessionToken, when you're using the Web Service you have to make the sessiontoken BY YOURSELF, and this can be just any string, but always have to be different, and google recommends to use UUID v4. So I found this video of a guy making the request using Flutter but I had to do it for my next.js app. Then I got to this npm library: uuid and managed the state of a component variable with useState, added it to the request every time text changes:

    import { v4 as uuidv4 } from 'uuid'
    ...
    const [sessiontoken, setSessiontoken] = useState(null)
    ...
    const handleInputChange = (text) => {
    if(sessiontoken===null){
      setSessiontoken(uuidv4())
    } ... }
    

    And then put back to its initial state once the option has been clicked, consulted (place details), and saved.

    ...
    setSessiontoken(null)