how to get postal code with react-places-autocomplete

Viewed 4836

I have a search bar with the Google Maps Places Autocomplete. I am using the npm package 'react-places-autocomplete' in Next.js.

Is there any way to get the postal code in handleSelect?

import { geocodeByAddress, getLatLng } from 'react-places-autocomplete';

export default function CP({...}: Props) {
 

  const handleSelect = async (address) => {
    const results = await geocodeByAddress(address);
    const latLng = await getLatLng(results[0]);
  };


  return (
      <LocationSearchInput
        address={state.address}
        visible={visible}
        handleChange={handleChange}
        handleSelect={handleSelect}
      />
  );
}


2 Answers

Simple answer: No, you can't directly get the postcode from the google places autocomplete service you can see the response object here.

Long answer: Yes with more calls.

In the prediction you will be given a property called a place_id, you can use this with other google services such as getDetails which will provide you with a PlaceResult where you can get address details such as lat and lng coordinates.

If you still can't get the address details you need this point you can use free a service like https://postcodes.io/ to then get the postcode from the lat and lng coordinates.

I have a full guide on how you can use postcodes with the JavaScript Google Places Api here


As for react-places-autocomplete:

I am not sure what it provides but if the module is anything like use-places-autocomplete, an easier solution would be to get the place_id from the prediction, use next.js's ssr capability and make the above requests server side and then return the postcode to your client side.

If you want to know any more about using the Google Places Autocomplete Service with react I suggest taking a look at this blog post/tutorial that I wrote about it: https://atomizedobjects.com/blog/react/how-to-use-google-autocomplete-with-react-hooks/

How I get the postal code:

import { geocodeByAddress, getLatLng, geocodeByPlaceId } from 'react-places-autocomplete';

  const handleSelect = async (address, placeId) => {
    const results = await geocodeByAddress(address);
    const latLng = await getLatLng(results[0]);
    const [place] = await geocodeByPlaceId(placeId);
    const { long_name: postalCode = '' } =
      place.address_components.find(c => c.types.includes('postal_code')) || {};
    console.log("postalCode",postalCode);
  };
Related