How Integrate NextJs with Google Places API for Client Use
Here is a solution for the integration of google API, specifically for text autocompletion in the client side. This strategy can be used to mitigate requests to your server, which would not be necessary.
Google provides an easier way of using the search from the server side, this “server-side” approach don’t get blocked by CORS.
Although I’m writing for NextJs, could be Vanilla Js or other framework. First, use the google documentation to Get your API key, I’m not going to in this article but create the API key is well documented online.
Inside the Next app, use the “<Script/>” tag to load a script and place inside the return function. It will look like this:
… return (<Scriptsrc=”https://maps.googleapis.com/maps/api/js?key=[your_key]&libraries=places&callback=initMap" strategy=’afterInteractive’></Script>)
The stragegy can be changed, it doesn’t matter at all.
This is where people mess around, look in the script there is a callback to a function called initMap. To make this work you will have to attach a function to the window. So…
Create a function called initMap, and then attach to the window.
function iniMap () { //paste the code from the google documentation}
if( typeof window!==”undefined”){ window.initMap = initMap;}
The typeof is because Next can execute this in a Node enviroment where there is no window, of course.
Then you read the Google documentation, create a div and use this
function google.maps.places.Autocomplete(element, options);
Your select element will be take over by autocompletion. Done!